fyrox_impl/utils/behavior/composite.rs
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
//! Composite node is a container for children nodes. Composite node could be either
//! `Sequence` or `Selector`. `Sequence` node will execute children nodes consecutively
//! until `Status::Failure` is returned from any descendant node. In other words `Sequence`
//! implement AND logical function. `Selector` node will execute children until `Status::Success`
//! is returned from any descendant node. In other worlds `Selector` implement OR logical
//! function.
use crate::{
core::{pool::Handle, visitor::prelude::*},
utils::behavior::{BehaviorNode, BehaviorTree},
};
/// Defines exact behavior of the composite node.
#[derive(Debug, PartialEq, Visit, Eq, Clone)]
pub enum CompositeNodeKind {
/// `Sequence` node will execute children nodes consecutively
/// until `Status::Failure` is returned from any descendant node. In other words `Sequence`
/// implement AND logical function.
Sequence,
/// `Selector` node will execute children until `Status::Success`
/// is returned from any descendant node. In other worlds `Selector` implement OR logical
/// function.
Selector,
}
impl Default for CompositeNodeKind {
fn default() -> Self {
Self::Sequence
}
}
/// See module docs.
#[derive(Debug, PartialEq, Visit, Eq, Clone)]
pub struct CompositeNode<B>
where
B: Clone,
{
/// A set of children.
pub children: Vec<Handle<BehaviorNode<B>>>,
/// Current kind of the node.
pub kind: CompositeNodeKind,
}
impl<B> Default for CompositeNode<B>
where
B: Clone,
{
fn default() -> Self {
Self {
children: Default::default(),
kind: Default::default(),
}
}
}
impl<B> CompositeNode<B>
where
B: Clone + 'static,
{
/// Creates new composite node of given kind and set of children nodes.
pub fn new(kind: CompositeNodeKind, children: Vec<Handle<BehaviorNode<B>>>) -> Self {
Self { children, kind }
}
/// Creates new sequence composite node with a set of children nodes.
pub fn new_sequence(children: Vec<Handle<BehaviorNode<B>>>) -> Self {
Self {
children,
kind: CompositeNodeKind::Sequence,
}
}
/// Creates new selector composite node with a set of children nodes.
pub fn new_selector(children: Vec<Handle<BehaviorNode<B>>>) -> Self {
Self {
children,
kind: CompositeNodeKind::Selector,
}
}
/// Adds self to the tree and return handle to self.
pub fn add_to(self, tree: &mut BehaviorTree<B>) -> Handle<BehaviorNode<B>> {
tree.add_node(BehaviorNode::Composite(self))
}
}