bevior_tree 0.11.0

Behavior tree plugin for Bevy.
Documentation
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
//! Nodes that depends on the condition of the bevy world().

use std::{fmt::Debug, sync::Mutex};

use bevy::ecs::{
    entity::Entity,
    system::{In, IntoSystem, System},
    world::World,
};

use crate::node::prelude::*;

pub mod variants;

pub mod prelude {
    pub use super::{
        CheckIf, ConditionalLoop, ElseFreeze, LoopCondChecker, LoopState, variants::prelude::*,
    };
}

pub type LoopCondChecker = dyn System<In = In<(Entity, LoopState)>, Out = bool>;

#[cfg_attr(feature = "serde", typetag::serde(tag = "type"))]
pub trait LoopCondCheckerBuilder: 'static + Debug + Send + Sync {
    fn build(&self) -> Box<LoopCondChecker>;
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug)]
pub struct LoopCountCondCheckerBuilder {
    max_count: usize,
}
#[cfg_attr(feature = "serde", typetag::serde)]
impl LoopCondCheckerBuilder for LoopCountCondCheckerBuilder {
    fn build(&self) -> Box<LoopCondChecker> {
        let max_count = self.max_count;
        Box::new(IntoSystem::into_system(
            move |In((_, loop_state)): In<(Entity, LoopState)>| loop_state.count < max_count,
        ))
    }
}

/// Node for conditional loop.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug)]
#[with_state(ConditionalLoopState)]
pub struct ConditionalLoop {
    child: Box<dyn Node>,
    checker_builder: Box<dyn LoopCondCheckerBuilder>,
    #[cfg_attr(feature = "serde", serde(skip))]
    checker_runtime: Mutex<Option<Box<LoopCondChecker>>>,
}
impl ConditionalLoop {
    pub fn new(child: impl Node, checker_builder: impl LoopCondCheckerBuilder) -> Self {
        Self {
            child: Box::new(child),
            checker_builder: Box::new(checker_builder),
            checker_runtime: Mutex::new(None),
        }
    }
    pub fn check(&self, world: &mut World, entity: Entity, loop_state: LoopState) -> bool {
        let mut checker_lock = self.checker_runtime.lock().expect("Failed to lock.");
        if checker_lock.is_none() {
            let mut new_checker = self.checker_builder.build();
            new_checker.initialize(world);
            *checker_lock = Some(new_checker);
        }
        checker_lock
            .as_mut()
            .expect("Checker not initialized.")
            .run((entity, loop_state), world)
            .expect("Failed to run checker system.")
    }
}
#[cfg_attr(feature = "serde", typetag::serde)]
impl Node for ConditionalLoop {
    fn begin(&self, world: &mut World, entity: Entity) -> NodeStatus {
        let state = ConditionalLoopState {
            loop_state: LoopState {
                count: 0,
                last_result: None,
            },
            child_status: NodeStatus::Beginning,
        };
        self.resume(world, entity, Box::new(state))
    }

    fn resume(&self, world: &mut World, entity: Entity, state: Box<dyn NodeState>) -> NodeStatus {
        let state = Self::downcast(state).expect("Invalid state type.");
        let state = match state.child_status {
            NodeStatus::Beginning => {
                if !self.check(world, entity, state.loop_state) {
                    return NodeStatus::Complete(
                        state.loop_state.last_result.unwrap_or(NodeResult::Failure),
                    );
                }
                ConditionalLoopState {
                    loop_state: state.loop_state,
                    child_status: self.child.begin(world, entity),
                }
            }
            NodeStatus::Pending(child_state) => ConditionalLoopState {
                loop_state: state.loop_state,
                child_status: self.child.resume(world, entity, child_state),
            },
            NodeStatus::Complete(result) => ConditionalLoopState {
                loop_state: state.loop_state.update(result),
                child_status: NodeStatus::Beginning,
            },
        };
        match &state.child_status {
            &NodeStatus::Beginning => self.resume(world, entity, Box::new(state)),
            &NodeStatus::Complete(_) => self.resume(world, entity, Box::new(state)),
            &NodeStatus::Pending(_) => NodeStatus::Pending(Box::new(state)),
        }
    }

    fn force_exit(&self, world: &mut World, entity: Entity, state: Box<dyn NodeState>) {
        let state = Self::downcast(state).expect("Invalid state type.");
        match state.child_status {
            NodeStatus::Pending(child_state) => self.child.force_exit(world, entity, child_state),
            _ => {}
        }
    }
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(NodeState, Debug, Clone, Copy, PartialEq, Eq)]
pub struct LoopState {
    count: usize,
    last_result: Option<NodeResult>,
}
impl LoopState {
    fn update(self, result: NodeResult) -> Self {
        Self {
            count: self.count + 1,
            last_result: Some(result),
        }
    }
}

/// State for [`ConditionalLoop`]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(NodeState, Debug)]
struct ConditionalLoopState {
    loop_state: LoopState,
    child_status: NodeStatus,
}

pub type CondChecker = dyn System<In = In<Entity>, Out = bool>;

#[cfg_attr(feature = "serde", typetag::serde(tag = "type"))]
pub trait CondCheckerBuilder: 'static + Debug + Send + Sync {
    fn build(&self) -> Box<CondChecker>;
}

/// State for [`CheckIf`]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(NodeState, Debug)]
struct CheckIfState;

/// Node that check the condition, then return it as [`NodeResult`].
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug)]
#[with_state(CheckIfState)]
pub struct CheckIf {
    checker_builder: Box<dyn CondCheckerBuilder>,
    #[cfg_attr(feature = "serde", serde(skip))]
    checker_runtime: Mutex<Option<Box<CondChecker>>>,
}
impl CheckIf {
    pub fn new(checker_builder: impl CondCheckerBuilder) -> Self {
        Self {
            checker_builder: Box::new(checker_builder),
            checker_runtime: Mutex::new(None),
        }
    }
    fn check(&self, world: &mut World, entity: Entity) -> bool {
        let mut checker_lock = self.checker_runtime.lock().expect("Failed to lock.");
        if checker_lock.is_none() {
            let mut new_checker = self.checker_builder.build();
            new_checker.initialize(world);
            *checker_lock = Some(new_checker);
        }
        checker_lock
            .as_mut()
            .expect("Checker not initialized.")
            .run(entity, world)
            .expect("Failed to run checker system.")
    }
}
#[cfg_attr(feature = "serde", typetag::serde)]
impl Node for CheckIf {
    fn begin(&self, world: &mut World, entity: Entity) -> NodeStatus {
        self.resume(world, entity, Box::new(CheckIfState))
    }
    fn resume(&self, world: &mut World, entity: Entity, state: Box<dyn NodeState>) -> NodeStatus {
        let _state = Self::downcast(state).expect("Invalid state type.");
        NodeStatus::Complete(if self.check(world, entity) {
            NodeResult::Success
        } else {
            NodeResult::Failure
        })
    }
    fn force_exit(&self, _world: &mut World, _entity: Entity, _state: Box<dyn NodeState>) {
        // never
    }
}

/// Node that run the child while condition matched, else freeze.
/// Freezes transition of the child sub-tree, not running task.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug)]
#[with_state(ElseFreezeState)]
pub struct ElseFreeze {
    child: Box<dyn Node>,
    checker_builder: Box<dyn CondCheckerBuilder>,
    #[cfg_attr(feature = "serde", serde(skip))]
    checker_runtime: Mutex<Option<Box<CondChecker>>>,
}
impl ElseFreeze {
    pub fn new(child: impl Node, checker_builder: impl CondCheckerBuilder) -> Self {
        Self {
            child: Box::new(child),
            checker_builder: Box::new(checker_builder),
            checker_runtime: Mutex::new(None),
        }
    }
    fn check(&self, world: &mut World, entity: Entity) -> bool {
        let mut checker_lock = self.checker_runtime.lock().expect("Failed to lock.");
        if checker_lock.is_none() {
            let mut new_checker = self.checker_builder.build();
            new_checker.initialize(world);
            *checker_lock = Some(new_checker);
        }
        checker_lock
            .as_mut()
            .expect("Checker not initialized.")
            .run(entity, world)
            .expect("Failed to run checker system.")
    }
}
#[cfg_attr(feature = "serde", typetag::serde)]
impl Node for ElseFreeze {
    fn begin(&self, world: &mut World, entity: Entity) -> NodeStatus {
        self.resume(
            world,
            entity,
            Box::new(ElseFreezeState {
                child_status: NodeStatus::Beginning,
            }),
        )
    }

    fn resume(&self, world: &mut World, entity: Entity, state: Box<dyn NodeState>) -> NodeStatus {
        let state = Self::downcast(state).expect("Invalid state.");
        if !self.check(world, entity) {
            return NodeStatus::Pending(Box::new(state));
        }
        let child_status = match state.child_status {
            NodeStatus::Beginning => self.child.begin(world, entity),
            NodeStatus::Pending(child_state) => self.child.resume(world, entity, child_state),
            NodeStatus::Complete(_) => {
                panic!("Invalid child status.")
            }
        };
        match &child_status {
            NodeStatus::Beginning => {
                panic!("Invalid child status.")
            }
            NodeStatus::Pending(_) => {
                NodeStatus::Pending(Box::new(ElseFreezeState { child_status }))
            }
            NodeStatus::Complete(_) => child_status,
        }
    }

    fn force_exit(&self, world: &mut World, entity: Entity, state: Box<dyn NodeState>) {
        let state = Self::downcast(state).expect("Invalid state.");
        match state.child_status {
            NodeStatus::Pending(child_state) => self.child.force_exit(world, entity, child_state),
            _ => {}
        }
    }
}

/// State for [`ElseFreeze`]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(NodeState, Debug)]
struct ElseFreezeState {
    child_status: NodeStatus,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tester_util::prelude::*;
    use bevy::state::app::StatesPlugin;

    #[derive(Component)]
    struct TestMarker;

    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Default, States)]
    enum TestStates {
        #[default]
        MainState,
        FreezeState,
    }

    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    #[derive(Debug)]
    struct TestMarkerExistsCondCheckerBuilder;
    #[cfg_attr(feature = "serde", typetag::serde)]
    impl CondCheckerBuilder for TestMarkerExistsCondCheckerBuilder {
        fn build(&self) -> Box<CondChecker> {
            Box::new(IntoSystem::into_system(
                |In(entity): In<Entity>, world: &World| -> bool {
                    world.entity(entity).contains::<TestMarker>()
                },
            ))
        }
    }

    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    #[derive(Debug)]
    struct TestStateMatcherCondCheckerBuilder {
        target_state: TestStates,
    }
    #[cfg_attr(feature = "serde", typetag::serde)]
    impl CondCheckerBuilder for TestStateMatcherCondCheckerBuilder {
        fn build(&self) -> Box<CondChecker> {
            let target_state = self.target_state;
            Box::new(IntoSystem::into_system(
                move |In(_): In<Entity>, state: Res<State<TestStates>>| -> bool {
                    *state.get() == target_state
                },
            ))
        }
    }

    #[test]
    fn test_repeat_count() {
        let mut app = App::new();
        app.add_plugins((TesterPlugin, BehaviorTreePlugin::default()));
        let task = TesterTask0::new(1, NodeResult::Success);
        let repeater = ConditionalLoop::new(task, LoopCountCondCheckerBuilder { max_count: 3 });
        let tree = BehaviorTree::from_node(
            repeater,
            &mut app.world_mut().resource_mut::<Assets<BehaviorTreeRoot>>(),
        );
        let _entity = app.world_mut().spawn(tree).id();
        app.update();
        app.update(); // 0
        app.update(); // 1
        app.update(); // 2, repeater complete
        let expected = TestLog {
            log: vec![
                TestLogEntry {
                    task_id: 0,
                    updated_count: 0,
                    frame: 1,
                },
                TestLogEntry {
                    task_id: 0,
                    updated_count: 0,
                    frame: 2,
                },
                TestLogEntry {
                    task_id: 0,
                    updated_count: 0,
                    frame: 3,
                },
            ],
        };
        let found = app.world().get_resource::<TestLog>().unwrap();
        assert!(
            found == &expected,
            "ConditionalLoop should repeat the task. found: {:?}",
            found
        );
    }

    #[test]
    fn test_check_if_false() {
        let mut app = App::new();
        app.add_plugins((TesterPlugin, BehaviorTreePlugin::default()));
        let task = CheckIf::new(TestMarkerExistsCondCheckerBuilder);
        let tree = BehaviorTree::from_node(
            task,
            &mut app.world_mut().resource_mut::<Assets<BehaviorTreeRoot>>(),
        );
        let entity = app.world_mut().spawn(tree).id();
        app.update();
        app.update();
        let tree_status = app.world().get::<TreeStatus>(entity);
        assert!(
            match tree_status {
                Some(&TreeStatus(NodeStatus::Complete(NodeResult::Failure))) => true,
                _ => false,
            },
            "CheckIf should match the result."
        );
    }

    #[test]
    fn test_check_if_true() {
        let mut app = App::new();
        app.add_plugins((TesterPlugin, BehaviorTreePlugin::default()));
        let task = CheckIf::new(TestMarkerExistsCondCheckerBuilder);
        let tree = BehaviorTree::from_node(
            task,
            &mut app.world_mut().resource_mut::<Assets<BehaviorTreeRoot>>(),
        );
        let entity = app.world_mut().spawn((tree, TestMarker)).id();
        app.update();
        app.update();
        let tree_status = app.world().get::<TreeStatus>(entity);
        assert!(
            match tree_status {
                Some(&TreeStatus(NodeStatus::Complete(NodeResult::Success))) => true,
                _ => false,
            },
            "CheckIf should match the result."
        );
    }

    #[test]
    fn test_conditional_freeze() {
        let mut app = App::new();
        app.add_plugins((StatesPlugin, TesterPlugin, BehaviorTreePlugin::default()));
        let task = TesterTask0::new(2, NodeResult::Success);
        let root = ElseFreeze::new(
            task,
            TestStateMatcherCondCheckerBuilder {
                target_state: TestStates::MainState,
            },
        );
        let tree = BehaviorTree::from_node(
            root,
            &mut app.world_mut().resource_mut::<Assets<BehaviorTreeRoot>>(),
        );
        let _entity = app.world_mut().spawn(tree).id();
        app.init_state::<TestStates>();
        app.update();
        app.update(); // 0
        app.world_mut()
            .get_resource_mut::<NextState<TestStates>>()
            .unwrap()
            .set(TestStates::FreezeState);
        app.update(); // 1
        app.update(); // 2
        app.world_mut()
            .get_resource_mut::<NextState<TestStates>>()
            .unwrap()
            .set(TestStates::MainState);
        app.update(); // 3, repeater complete
        let expected = TestLog {
            log: vec![
                TestLogEntry {
                    task_id: 0,
                    updated_count: 0,
                    frame: 1,
                },
                TestLogEntry {
                    task_id: 0,
                    updated_count: 1,
                    frame: 2,
                },
                TestLogEntry {
                    task_id: 0,
                    updated_count: 2,
                    frame: 3,
                },
                TestLogEntry {
                    task_id: 0,
                    updated_count: 3,
                    frame: 4,
                },
            ],
        };
        let found = app.world().get_resource::<TestLog>().unwrap();
        assert!(
            found == &expected,
            "ElseFreeze should match the result. found: {:?}",
            found
        );
    }
}