forked from BehaviorTree/BehaviorTree.CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree_node.h
294 lines (242 loc) · 9.7 KB
/
tree_node.h
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
/* Copyright (C) 2015-2018 Michele Colledanchise - All Rights Reserved
* Copyright (C) 2018-2020 Davide Faconti, Eurecat - All Rights Reserved
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef BEHAVIORTREECORE_TREENODE_H
#define BEHAVIORTREECORE_TREENODE_H
#include <condition_variable>
#include <mutex>
#include "behaviortree_cpp_v3/utils/signal.h"
#include "behaviortree_cpp_v3/exceptions.h"
#include "behaviortree_cpp_v3/basic_types.h"
#include "behaviortree_cpp_v3/blackboard.h"
#include "behaviortree_cpp_v3/utils/strcat.hpp"
#ifdef _MSC_VER
#pragma warning(disable : 4127)
#endif
namespace BT
{
/// This information is used mostly by the XMLParser.
struct TreeNodeManifest
{
NodeType type;
std::string registration_ID;
PortsList ports;
};
typedef std::unordered_map<std::string, std::string> PortsRemapping;
struct NodeConfiguration
{
NodeConfiguration()
{
}
Blackboard::Ptr blackboard;
PortsRemapping input_ports;
PortsRemapping output_ports;
};
/// Abstract base class for Behavior Tree Nodes
class TreeNode
{
public:
typedef std::shared_ptr<TreeNode> Ptr;
/**
* @brief TreeNode main constructor.
*
* @param name name of the instance, not the type.
* @param config information about input/output ports. See NodeConfiguration
*
* Note: If your custom node has ports, the derived class must implement:
*
* static PortsList providedPorts();
*/
TreeNode(std::string name, NodeConfiguration config);
virtual ~TreeNode() = default;
/// The method that should be used to invoke tick() and setStatus();
virtual BT::NodeStatus executeTick();
/// The method used to interrupt the execution of a RUNNING node.
/// Only Async nodes that may return RUNNING should implement it.
virtual void halt() = 0;
bool isHalted() const;
NodeStatus status() const;
/// Name of the instance, not the type
const std::string& name() const;
/// Blocking function that will sleep until the setStatus() is called with
/// either RUNNING, FAILURE or SUCCESS.
BT::NodeStatus waitValidStatus();
virtual NodeType type() const = 0;
using StatusChangeSignal = Signal<TimePoint, const TreeNode&, NodeStatus, NodeStatus>;
using StatusChangeSubscriber = StatusChangeSignal::Subscriber;
using StatusChangeCallback = StatusChangeSignal::CallableFunction;
/**
* @brief subscribeToStatusChange is used to attach a callback to a status change.
* When StatusChangeSubscriber goes out of scope (it is a shared_ptr) the callback
* is unsubscribed automatically.
*
* @param callback The callback to be execute when status change.
*
* @return the subscriber handle.
*/
StatusChangeSubscriber subscribeToStatusChange(StatusChangeCallback callback);
// get an unique identifier of this instance of treeNode
uint16_t UID() const;
/// registrationName is the ID used by BehaviorTreeFactory to create an instance.
const std::string& registrationName() const;
/// Configuration passed at construction time. Can never change after the
/// creation of the TreeNode instance.
const NodeConfiguration& config() const;
/** Read an input port, which, in practice, is an entry in the blackboard.
* If the blackboard contains a std::string and T is not a string,
* convertFromString<T>() is used automatically to parse the text.
*
* @param key the identifier (before remapping) of the port.
* @return false if an error occurs.
*/
template <typename T>
Result getInput(const std::string& key, T& destination) const;
/** Same as bool getInput(const std::string& key, T& destination)
* but using optional.
*/
template <typename T>
Optional<T> getInput(const std::string& key) const
{
T out;
auto res = getInput(key, out);
return (res) ? Optional<T>(out) : nonstd::make_unexpected(res.error());
}
template <typename T>
Result setOutput(const std::string& key, const T& value);
// function provide mostrly for debugging purpose to see the raw value
// in the port (no remapping and no conversion to a type)
StringView getRawPortValue(const std::string &key) const;
/// Check a string and return true if it matches either one of these
/// two patterns: {...} or ${...}
static bool isBlackboardPointer(StringView str);
static StringView stripBlackboardPointer(StringView str);
static Optional<StringView> getRemappedKey(StringView port_name, StringView remapping_value);
protected:
/// Method to be implemented by the user
virtual BT::NodeStatus tick() = 0;
friend class BehaviorTreeFactory;
friend class DecoratorNode;
friend class ControlNode;
friend class Tree;
// Only BehaviorTreeFactory should call this
void setRegistrationID(StringView ID)
{
registration_ID_.assign(ID.data(), ID.size());
}
void modifyPortsRemapping(const PortsRemapping& new_remapping);
void setStatus(NodeStatus new_status);
private:
const std::string name_;
NodeStatus status_;
std::condition_variable state_condition_variable_;
mutable std::mutex state_mutex_;
StatusChangeSignal state_change_signal_;
const uint16_t uid_;
NodeConfiguration config_;
std::string registration_ID_;
};
//-------------------------------------------------------
template <typename T>
inline Result TreeNode::getInput(const std::string& key, T& destination) const
{
auto remap_it = config_.input_ports.find(key);
if (remap_it == config_.input_ports.end())
{
return nonstd::make_unexpected(StrCat("getInput() failed because "
"NodeConfiguration::input_ports "
"does not contain the key: [",
key, "]"));
}
auto remapped_res = getRemappedKey(key, remap_it->second);
try
{
if (!remapped_res)
{
destination = convertFromString<T>(remap_it->second);
return {};
}
const auto& remapped_key = remapped_res.value();
if (!config_.blackboard)
{
return nonstd::make_unexpected("getInput() trying to access a Blackboard(BB) entry, "
"but BB is invalid");
}
const Any* val = config_.blackboard->getAny(static_cast<std::string>(remapped_key));
if (val && val->empty() == false)
{
if (std::is_same<T, std::string>::value == false && val->type() == typeid(std::string))
{
destination = convertFromString<T>(val->cast<std::string>());
}
else
{
destination = val->cast<T>();
}
return {};
}
return nonstd::make_unexpected(StrCat("getInput() failed because it was unable to find the "
"key [",
key, "] remapped to [", remapped_key, "]"));
}
catch (std::exception& err)
{
return nonstd::make_unexpected(err.what());
}
}
template <typename T>
inline Result TreeNode::setOutput(const std::string& key, const T& value)
{
if (!config_.blackboard)
{
return nonstd::make_unexpected("setOutput() failed: trying to access a "
"Blackboard(BB) entry, but BB is invalid");
}
auto remap_it = config_.output_ports.find(key);
if (remap_it == config_.output_ports.end())
{
return nonstd::make_unexpected(StrCat("setOutput() failed: NodeConfiguration::output_ports "
"does not "
"contain the key: [",
key, "]"));
}
StringView remapped_key = remap_it->second;
if (remapped_key == "=")
{
remapped_key = key;
}
if (isBlackboardPointer(remapped_key))
{
remapped_key = stripBlackboardPointer(remapped_key);
}
config_.blackboard->set(static_cast<std::string>(remapped_key), value);
return {};
}
// Utility function to fill the list of ports using T::providedPorts();
template <typename T>
inline void assignDefaultRemapping(NodeConfiguration& config)
{
for (const auto& it : getProvidedPorts<T>())
{
const auto& port_name = it.first;
const auto direction = it.second.direction();
if (direction != PortDirection::OUTPUT)
{
config.input_ports[port_name] = "=";
}
if (direction != PortDirection::INPUT)
{
config.output_ports[port_name] = "=";
}
}
}
} // namespace BT
#endif