|
| 1 | +#include <gtest/gtest.h> |
| 2 | +#include "behaviortree_cpp/bt_factory.h" |
| 3 | + |
| 4 | +using namespace BT; |
| 5 | + |
| 6 | +enum class Color |
| 7 | +{ |
| 8 | + Red = 0, |
| 9 | + Blue = 1, |
| 10 | + Green = 2, |
| 11 | + Undefined |
| 12 | +}; |
| 13 | + |
| 14 | +static const char* ToStr(const Color& c) |
| 15 | +{ |
| 16 | + switch (c) { |
| 17 | + case Color::Red: return "Red"; |
| 18 | + case Color::Blue: return "Blue"; |
| 19 | + case Color::Green: return "Green"; |
| 20 | + case Color::Undefined: return "Undefined"; |
| 21 | + } |
| 22 | + return nullptr; |
| 23 | +} |
| 24 | + |
| 25 | + |
| 26 | +class ActionEnum : public SyncActionNode |
| 27 | +{ |
| 28 | +public: |
| 29 | + ActionEnum(const std::string& name, const NodeConfig& config) : |
| 30 | + SyncActionNode(name, config) |
| 31 | + {} |
| 32 | + |
| 33 | + NodeStatus tick() override |
| 34 | + { |
| 35 | + getInput("color", color); |
| 36 | + std::cout << "Node: " << name() << " has color : " << ToStr(color) << std::endl; |
| 37 | + return NodeStatus::SUCCESS; |
| 38 | + } |
| 39 | + |
| 40 | + static PortsList providedPorts() |
| 41 | + { |
| 42 | + return {BT::InputPort<Color>("color")}; |
| 43 | + } |
| 44 | + |
| 45 | + Color color = Color::Undefined; |
| 46 | +}; |
| 47 | + |
| 48 | +TEST(Enums, StrintToEnum) |
| 49 | +{ |
| 50 | + std::string xml_txt = R"( |
| 51 | + <root BTCPP_format="4" > |
| 52 | + <BehaviorTree ID="Main"> |
| 53 | + <Sequence> |
| 54 | + <Script code=" my_color := Red "/> |
| 55 | + <ActionEnum name="maybe_blue" color="Blue"/> |
| 56 | + <ActionEnum name="maybe_green" color="2"/> |
| 57 | + <ActionEnum name="maybe_red" color="{my_color}"/> |
| 58 | + </Sequence> |
| 59 | + </BehaviorTree> |
| 60 | + </root>)"; |
| 61 | + |
| 62 | + BehaviorTreeFactory factory; |
| 63 | + factory.registerNodeType<ActionEnum>("ActionEnum"); |
| 64 | + factory.registerScriptingEnums<Color>(); |
| 65 | + |
| 66 | + auto tree = factory.createTreeFromText(xml_txt); |
| 67 | + |
| 68 | + NodeStatus status = tree.tickWhileRunning(); |
| 69 | + |
| 70 | + ASSERT_EQ(status, NodeStatus::SUCCESS); |
| 71 | + |
| 72 | + for(const auto& node: tree.subtrees.front()->nodes) |
| 73 | + { |
| 74 | + if(auto enum_node = dynamic_cast<ActionEnum*>(node.get())) |
| 75 | + { |
| 76 | + if(enum_node->name() == "maybe_red") |
| 77 | + { |
| 78 | + ASSERT_EQ(Color::Red, enum_node->color); |
| 79 | + } |
| 80 | + else if(enum_node->name() == "maybe_green") |
| 81 | + { |
| 82 | + ASSERT_EQ(Color::Green, enum_node->color); |
| 83 | + } |
| 84 | + else if(enum_node->name() == "maybe_blue") |
| 85 | + { |
| 86 | + ASSERT_EQ(Color::Blue, enum_node->color); |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | +} |
| 91 | + |
0 commit comments