2
3
4
5
6
7
8
9
10
11
12
17#include "behaviortree_cpp/behavior_tree.h"
18#ifdef BTCPP_SYSTEM_JSON
19#include <nlohmann/json.hpp>
21#include "behaviortree_cpp/contrib/json.hpp"
23#include "behaviortree_cpp/contrib/magic_enum.hpp"
24#include "behaviortree_cpp/utils/polymorphic_cast_registry.hpp"
30#include <unordered_map>
39template <
typename T,
typename... Args>
40inline NodeBuilder CreateBuilder(Args... args)
42 return [=](
const std::string& name,
const NodeConfig& config) {
43 return TreeNode::Instantiate<T, Args...>(name, config, args...);
49 PortsList portlist = getProvidedPorts<T>())
51 if constexpr(has_static_method_metadata<T>::value)
53 return { getType<T>(), ID, portlist, T::metadata() };
55 return { getType<T>(), ID, portlist, {} };
58#ifdef BT_PLUGIN_EXPORT
61#define BTCPP_EXPORT extern "C" __declspec(dllexport)
64#define BTCPP_EXPORT extern "C" __attribute__((visibility("default")))
68#define BTCPP_EXPORT static
71
72
73
74
75
76
77
78
79
80
81
82
83
84
87#define BT_REGISTER_NODES(factory)
88 BTCPP_EXPORT void BT_RegisterNodesFromPlugin(BT::BehaviorTreeFactory& factory)
91constexpr const char* PLUGIN_SYMBOL =
"BT_RegisterNodesFromPlugin";
93bool WildcardMatch(
const std::string& str, StringView filter);
96
97
98
105 using Ptr = std::shared_ptr<
Subtree>;
106 std::vector<TreeNode::Ptr> nodes;
108 std::string instance_name;
112 std::vector<Subtree::Ptr> subtrees;
113 std::unordered_map<std::string, TreeNodeManifest> manifests;
117 Tree(
const Tree&) =
delete;
118 Tree& operator=(
const Tree&) =
delete;
120 Tree(
Tree&& other) =
default;
121 Tree& operator=(
Tree&& other) =
default;
130
131
132
133
134
135
136
137 bool sleep(std::chrono::system_clock::duration timeout);
140
141
145
146
147
148
149
159
160
161
162
174 void applyVisitor(
const std::function<
void(
const TreeNode*)>& visitor)
const;
177 void applyVisitor(
const std::function<
void(
TreeNode*)>& visitor);
190 std::vector<
const TreeNode*> nodes;
191 for(
auto const& subtree : subtrees)
193 for(
auto const& node : subtree->nodes)
195 if(
auto node_recast =
dynamic_cast<
const NodeType*>(node.get()))
197 if(WildcardMatch(node->fullPath(), wildcard_filter))
199 nodes.push_back(node.get());
215 ONCE_UNLESS_WOKEN_UP,
219 NodeStatus tickRoot(TickOption opt, std::chrono::milliseconds sleep_time);
224 void remapManifestPointers();
226 uint16_t uid_counter_ = 0;
232
233
234
235
236
237
241 BehaviorTreeFactory();
242 ~BehaviorTreeFactory();
254
255
256
257
260 template <
typename T>
261 void registerBuilder(
const std::string& ID,
const NodeBuilder& builder)
263 auto manifest = CreateManifest<T>(ID);
264 registerBuilder(manifest, builder);
268
269
270
271
272
273
274
277 PortsList ports = {});
279
280
281
282
283
284
285
288 PortsList ports = {});
290
291
292
293
294
295
296
299 PortsList ports = {});
302
303
304
305
309
310
311
315
316
317
318
319
320
321
322
323
335
336
340
341
342
343
344
345
346
351
352
353 template <
typename T,
typename... ExtraArgs>
354 void registerNodeType(
const std::string& ID,
const PortsList& ports, ExtraArgs... args)
360 "[registerNode]: accepts only classed derived from either "
362 "DecoratorNode, ControlNode or ConditionNode");
364 constexpr bool default_constructable =
365 std::is_constructible<T,
const std::string&>::value;
366 constexpr bool param_constructable =
367 std::is_constructible<T,
const std::string&,
const NodeConfig&,
368 ExtraArgs...>::value;
371 static_assert(!std::is_abstract<T>::value,
372 "[registerNode]: Some methods are pure virtual. "
373 "Did you override the methods tick() and halt()?");
375 static_assert(default_constructable || param_constructable,
376 "[registerNode]: the registered class must have at least one of these two constructors:\n"
377 " (const std::string&, const NodeConfig&) or (const std::string&)\n"
378 "Check also if the constructor is public!)");
381 registerBuilder(CreateManifest<T>(ID, ports), CreateBuilder<T>(args...));
385
386
387
388
389 template <
typename T,
typename... ExtraArgs>
392 if constexpr(std::is_abstract_v<T>)
395 static_assert(!std::is_abstract_v<T>,
"The Node type can't be abstract. "
396 "Did you forget to implement an abstract "
397 "method in the derived class?");
401 constexpr bool param_constructable =
402 std::is_constructible<T,
const std::string&,
const NodeConfig&,
403 ExtraArgs...>::value;
404 constexpr bool has_static_ports_list = has_static_method_providedPorts<T>::value;
407 static_assert(!(param_constructable && !has_static_ports_list),
408 "[registerNode]: you MUST implement the static method:\n"
409 " PortsList providedPorts();\n");
414 static_assert(!(has_static_ports_list && !param_constructable
415 &&
sizeof...(ExtraArgs) > 0),
416 "[registerNode]: the constructor is NOT compatible with the "
417 "arguments provided.\n"
418 "Verify that the types of the extra arguments passed to "
419 "registerNodeType match\n"
420 "the constructor signature: "
421 "(const std::string&, const NodeConfig&, ...)\n");
423 static_assert(!(has_static_ports_list && !param_constructable
424 &&
sizeof...(ExtraArgs) == 0),
425 "[registerNode]: since you have a static method providedPorts(),\n"
426 "you MUST add a constructor with signature:\n"
427 "(const std::string&, const NodeConfig&)\n");
430 registerNodeType<T>(ID, getProvidedPorts<T>(), args...);
444
445
446
447
448
449
450
451
452
453
458
459
460
461
462
463
464
465
466
467
473 Blackboard::Ptr blackboard = Blackboard::create());
480
481
482
483
484
485
486
487
488
489
490
491
495
496
497
498
499
500
501
502 template <
typename EnumType>
505 constexpr auto entries = magic_enum::enum_entries<EnumType>();
506 for(
const auto& it : entries)
508 registerScriptingEnum(it.second,
static_cast<
int>(it.first));
512 void clearSubstitutionRules();
518
519
520
521
522
523
524
525
526
527
531
532
533
534
535
536
540
541
546
547
548
549
550
551
552
553
554
555
556
557
558
559 template <
typename Derived,
typename Base>
566
567
568
569
570
571
576
577
578
579
580
586 std::unique_ptr<PImpl> _p;
590
591
592
593
594
598
599
600
601
602
603
607
608
609
610
611
612
616
617
618
622
623
624
#define BTCPP_EXPORT
Definition: bt_factory.h:68
The ActionNodeBase is the base class to use to create any kind of action. A particular derived class ...
Definition: action_node.h:35
The BehaviorTreeFactory is used to create instances of a TreeNode at run-time.
Definition: bt_factory.h:239
void addSubstitutionRule(StringView filter, SubstitutionRule rule)
addSubstitutionRule replace a node with another one when the tree is created. If the rule ia a string...
void registerSimpleCondition(const std::string &ID, const SimpleConditionNode::TickFunctor &tick_functor, PortsList ports={})
registerSimpleCondition help you register nodes of type SimpleConditionNode.
std::shared_ptr< PolymorphicCastRegistry > polymorphicCastRegistryPtr() const
Get a shared pointer to the polymorphic cast registry.
void registerBuilder(const TreeNodeManifest &manifest, const NodeBuilder &builder)
void loadSubstitutionRuleFromJSON(const std::string &json_text)
loadSubstitutionRuleFromJSON will parse a JSON file to create a set of substitution rules....
void registerNodeType(const std::string &ID, ExtraArgs... args)
Definition: bt_factory.h:390
void clearRegisteredBehaviorTrees()
Clear previously-registered behavior trees.
void registerPolymorphicCast()
Register a polymorphic cast relationship between Derived and Base types.
Definition: bt_factory.h:560
Tree createTreeFromText(const std::string &text, Blackboard::Ptr blackboard=Blackboard::create())
createTreeFromText will parse the XML directly from string. The XML needs to contain either a single ...
PolymorphicCastRegistry & polymorphicCastRegistry()
Access the polymorphic cast registry.
std::vector< std::string > registeredBehaviorTrees() const
void registerBehaviorTreeFromText(const std::string &xml_text)
const std::unordered_map< std::string, SubstitutionRule > & substitutionRules() const
substitutionRules return the current substitution rules.
void registerScriptingEnum(StringView name, int value)
Add an Enum to the scripting language. For instance if you do:
void registerSimpleAction(const std::string &ID, const SimpleActionNode::TickFunctor &tick_functor, PortsList ports={})
registerSimpleAction help you register nodes of type SimpleActionNode.
void registerScriptingEnums()
registerScriptingEnums is syntactic sugar to automatically register multiple enums....
Definition: bt_factory.h:503
void registerBehaviorTreeFromFile(const std::filesystem::path &filename)
registerBehaviorTreeFromFile. Load the definition of an entire behavior tree, but don't instantiate i...
const std::unordered_map< std::string, NodeBuilder > & builders() const
All the builders. Made available mostly for debug purposes.
const std::set< std::string > & builtinNodes() const
List of builtin IDs.
void addMetadataToManifest(const std::string &node_id, const KeyValueVector &metadata)
const std::unordered_map< std::string, TreeNodeManifest > & manifests() const
Manifests of all the registered TreeNodes.
std::unique_ptr< TreeNode > instantiateTreeNode(const std::string &name, const std::string &ID, const NodeConfig &config) const
instantiateTreeNode creates an instance of a previously registered TreeNode.
void registerNodeType(const std::string &ID, const PortsList &ports, ExtraArgs... args)
Definition: bt_factory.h:354
Tree createTreeFromFile(const std::filesystem::path &file_path, Blackboard::Ptr blackboard=Blackboard::create())
createTreeFromFile will parse the XML from a given file. The XML needs to contain either a single <Be...
void registerSimpleDecorator(const std::string &ID, const SimpleDecoratorNode::TickFunctor &tick_functor, PortsList ports={})
registerSimpleDecorator help you register nodes of type SimpleDecoratorNode.
bool unregisterBuilder(const std::string &ID)
Remove a registered ID.
void registerFromPlugin(const std::string &file_path)
registerFromPlugin load a shared library and execute the function BT_REGISTER_NODES (see macro).
void registerFromROSPlugins()
registerFromROSPlugins finds all shared libraries that export ROS plugins for behaviortree_cpp,...
The Blackboard is the mechanism used by BehaviorTrees to exchange typed data.
Definition: blackboard.h:39
The ConditionNode is a leaf node used to check a condition.
Definition: condition_node.h:32
The ControlNode is the base class for nodes that can have multiple children.
Definition: control_node.h:32
The DecoratorNode is the base class for nodes that have exactly one child.
Definition: decorator_node.h:19
The BehaviorTreeParser is a class used to read the model of a BehaviorTree from file or text and inst...
Definition: bt_parser.h:28
Registry for polymorphic shared_ptr cast relationships.
Definition: polymorphic_cast_registry.hpp:47
The SimpleActionNode provides an easy to use SyncActionNode. The user should simply provide a callbac...
Definition: action_node.h:89
The SimpleConditionNode provides an easy to use ConditionNode. The user should simply provide a callb...
Definition: condition_node.h:66
The SimpleDecoratorNode provides an easy to use DecoratorNode. The user should simply provide a callb...
Definition: decorator_node.h:68
Struct used to store a tree. If this object goes out of scope, the tree is destroyed.
Definition: bt_factory.h:100
std::shared_ptr< WakeUpSignal > wakeUpSignal() const
Returns the shared WakeUpSignal used by this tree. This can be used to check for preemption externall...
NodeStatus tickOnce()
by default, tickOnce() sends a single tick, BUT as long as there is at least one node of the tree inv...
std::vector< const TreeNode * > getNodesByPath(StringView wildcard_filter) const
Definition: bt_factory.h:188
NodeStatus tickWhileRunning(std::chrono::milliseconds sleep_time=std::chrono::milliseconds(10))
NodeStatus tickExactlyOnce()
bool sleep(std::chrono::system_clock::duration timeout)
Sleep for a certain amount of time. This sleep could be interrupted by the methods TreeNode::emitWake...
void emitWakeUpSignal()
Wake up the tree. This will interrupt the sleep() method.
Abstract base class for Behavior Tree Nodes.
Definition: tree_node.h:154
Definition: wakeup_signal.hpp:13
Definition: action_node.h:24
nlohmann::json ExportTreeToJSON(const BT::Tree &tree)
ExportTreeToJSON it calls ExportBlackboardToJSON for all the blackboards in the tree.
NodeStatus
Definition: basic_types.h:34
std::vector< Blackboard::Ptr > BlackboardBackup(const BT::Tree &tree)
BlackboardBackup uses Blackboard::cloneInto to backup all the blackboards of the tree.
void ImportTreeFromJSON(const nlohmann::json &json, BT::Tree &tree)
ImportTreeFromJSON it calls ImportBlackboardFromJSON for all the blackboards in the tree.
void BlackboardRestore(const std::vector< Blackboard::Ptr > &backup, BT::Tree &tree)
BlackboardRestore uses Blackboard::cloneInto to restore all the blackboards of the tree.
void BlackboardClone(const Blackboard &src, Blackboard &dst)
BlackboardClone make a copy of the content of the blackboard.
Definition: tree_node.h:105
Definition: bt_factory.h:104
This information is used mostly by the XMLParser.
Definition: tree_node.h:37