-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathsmac_planner_2d.cpp
More file actions
452 lines (403 loc) · 16.2 KB
/
Copy pathsmac_planner_2d.cpp
File metadata and controls
452 lines (403 loc) · 16.2 KB
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
// Copyright (c) 2020, Samsung Research America
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License. Reserved.
#include <string>
#include <memory>
#include <vector>
#include <limits>
#include <algorithm>
#include "nav2_smac_planner/smac_planner_2d.hpp"
#include "nav2_util/geometry_utils.hpp"
// #define BENCHMARK_TESTING
namespace nav2_smac_planner
{
using namespace std::chrono; // NOLINT
using rcl_interfaces::msg::ParameterType;
using std::placeholders::_1;
SmacPlanner2D::SmacPlanner2D()
: _a_star(nullptr),
_collision_checker(nullptr, 1, nullptr),
_smoother(nullptr),
_costmap(nullptr),
_costmap_downsampler(nullptr)
{
}
SmacPlanner2D::~SmacPlanner2D()
{
RCLCPP_INFO(
_logger, "Destroying plugin %s of type SmacPlanner2D",
_name.c_str());
}
void SmacPlanner2D::configure(
const rclcpp_lifecycle::LifecycleNode::WeakPtr & parent,
std::string name, std::shared_ptr<tf2_ros::Buffer>/*tf*/,
std::shared_ptr<nav2_costmap_2d::Costmap2DROS> costmap_ros)
{
_node = parent;
auto node = parent.lock();
_logger = node->get_logger();
_clock = node->get_clock();
_costmap = costmap_ros->getCostmap();
_name = name;
_global_frame = costmap_ros->getGlobalFrameID();
RCLCPP_INFO(_logger, "Configuring %s of type SmacPlanner2D", name.c_str());
// General planner params
nav2_util::declare_parameter_if_not_declared(
node, name + ".tolerance", rclcpp::ParameterValue(0.125));
_tolerance = static_cast<float>(node->get_parameter(name + ".tolerance").as_double());
nav2_util::declare_parameter_if_not_declared(
node, name + ".downsample_costmap", rclcpp::ParameterValue(false));
node->get_parameter(name + ".downsample_costmap", _downsample_costmap);
nav2_util::declare_parameter_if_not_declared(
node, name + ".downsampling_factor", rclcpp::ParameterValue(1));
node->get_parameter(name + ".downsampling_factor", _downsampling_factor);
nav2_util::declare_parameter_if_not_declared(
node, name + ".cost_travel_multiplier", rclcpp::ParameterValue(1.0));
node->get_parameter(name + ".cost_travel_multiplier", _search_info.cost_penalty);
nav2_util::declare_parameter_if_not_declared(
node, name + ".allow_unknown", rclcpp::ParameterValue(true));
node->get_parameter(name + ".allow_unknown", _allow_unknown);
nav2_util::declare_parameter_if_not_declared(
node, name + ".max_iterations", rclcpp::ParameterValue(1000000));
node->get_parameter(name + ".max_iterations", _max_iterations);
nav2_util::declare_parameter_if_not_declared(
node, name + ".max_on_approach_iterations", rclcpp::ParameterValue(1000));
node->get_parameter(name + ".max_on_approach_iterations", _max_on_approach_iterations);
nav2_util::declare_parameter_if_not_declared(
node, name + ".terminal_checking_interval", rclcpp::ParameterValue(5000));
node->get_parameter(name + ".terminal_checking_interval", _terminal_checking_interval);
nav2_util::declare_parameter_if_not_declared(
node, name + ".use_final_approach_orientation", rclcpp::ParameterValue(false));
node->get_parameter(name + ".use_final_approach_orientation", _use_final_approach_orientation);
nav2_util::declare_parameter_if_not_declared(
node, name + ".max_planning_time", rclcpp::ParameterValue(2.0));
node->get_parameter(name + ".max_planning_time", _max_planning_time);
// Note that we need to declare it here to prevent the parameter from being declared in the
// dynamic reconfigure callback
nav2_util::declare_parameter_if_not_declared(
node, "service_introspection_mode", rclcpp::ParameterValue("disabled"));
_motion_model = MotionModel::TWOD;
if (_max_on_approach_iterations <= 0) {
RCLCPP_INFO(
_logger, "On approach iteration selected as <= 0, "
"disabling tolerance and on approach iterations.");
_max_on_approach_iterations = std::numeric_limits<int>::max();
}
if (_max_iterations <= 0) {
RCLCPP_INFO(
_logger, "maximum iteration selected as <= 0, "
"disabling maximum iterations.");
_max_iterations = std::numeric_limits<int>::max();
}
// Initialize collision checker
_collision_checker = GridCollisionChecker(costmap_ros, 1 /*for 2D, most be 1*/, node);
_collision_checker.setFootprint(
costmap_ros->getRobotFootprint(),
true /*for 2D, most use radius*/,
0.0 /*for 2D cost at inscribed isn't relevant*/);
// Initialize A* template
_a_star = std::make_unique<AStarAlgorithm<Node2D>>(_motion_model, _search_info);
_a_star->initialize(
_allow_unknown,
_max_iterations,
_max_on_approach_iterations,
_terminal_checking_interval,
_max_planning_time,
0.0 /*unused for 2D*/,
1.0 /*unused for 2D*/);
// Initialize path smoother
SmootherParams params;
params.get(node, name);
params.holonomic_ = true; // So smoother will treat this as a grid search
_smoother = std::make_unique<Smoother>(params);
_smoother->initialize(1e-50 /*No valid minimum turning radius for 2D*/);
// Initialize costmap downsampler
if (_downsample_costmap && _downsampling_factor > 1) {
std::string topic_name = "downsampled_costmap";
_costmap_downsampler = std::make_unique<CostmapDownsampler>();
_costmap_downsampler->on_configure(
node, _global_frame, topic_name, _costmap, _downsampling_factor);
}
_raw_plan_publisher = node->create_publisher<nav_msgs::msg::Path>("unsmoothed_plan", 1);
RCLCPP_INFO(
_logger, "Configured plugin %s of type SmacPlanner2D with "
"tolerance %.2f, maximum iterations %i, "
"max on approach iterations %i, and %s.",
_name.c_str(), _tolerance, _max_iterations, _max_on_approach_iterations,
_allow_unknown ? "allowing unknown traversal" : "not allowing unknown traversal");
}
void SmacPlanner2D::activate()
{
RCLCPP_INFO(
_logger, "Activating plugin %s of type SmacPlanner2D",
_name.c_str());
_raw_plan_publisher->on_activate();
if (_costmap_downsampler) {
_costmap_downsampler->on_activate();
}
auto node = _node.lock();
// Add callback for dynamic parameters
_dyn_params_handler = node->add_on_set_parameters_callback(
std::bind(&SmacPlanner2D::dynamicParametersCallback, this, _1));
}
void SmacPlanner2D::deactivate()
{
RCLCPP_INFO(
_logger, "Deactivating plugin %s of type SmacPlanner2D",
_name.c_str());
_raw_plan_publisher->on_deactivate();
if (_costmap_downsampler) {
_costmap_downsampler->on_deactivate();
}
// shutdown dyn_param_handler
auto node = _node.lock();
if (_dyn_params_handler && node) {
node->remove_on_set_parameters_callback(_dyn_params_handler.get());
}
_dyn_params_handler.reset();
}
void SmacPlanner2D::cleanup()
{
RCLCPP_INFO(
_logger, "Cleaning up plugin %s of type SmacPlanner2D",
_name.c_str());
_a_star.reset();
_smoother.reset();
if (_costmap_downsampler) {
_costmap_downsampler->on_cleanup();
_costmap_downsampler.reset();
}
_raw_plan_publisher.reset();
}
nav_msgs::msg::Path SmacPlanner2D::createPlan(
const geometry_msgs::msg::PoseStamped & start,
const geometry_msgs::msg::PoseStamped & goal,
std::function<bool()> cancel_checker)
{
std::lock_guard<std::mutex> lock_reinit(_mutex);
steady_clock::time_point a = steady_clock::now();
std::unique_lock<nav2_costmap_2d::Costmap2D::mutex_t> lock(*(_costmap->getMutex()));
// Downsample costmap, if required
nav2_costmap_2d::Costmap2D * costmap = _costmap;
if (_costmap_downsampler) {
costmap = _costmap_downsampler->downsample(_downsampling_factor);
_collision_checker.setCostmap(costmap);
}
// Set collision checker and costmap information
_a_star->setCollisionChecker(&_collision_checker);
// Set starting point
float mx_start, my_start, mx_goal, my_goal;
if (!costmap->worldToMapContinuous(
start.pose.position.x,
start.pose.position.y,
mx_start,
my_start))
{
throw nav2_core::StartOutsideMapBounds(
"Start Coordinates of(" + std::to_string(start.pose.position.x) + ", " +
std::to_string(start.pose.position.y) + ") was outside bounds");
}
_a_star->setStart(mx_start, my_start, 0);
// Set goal point
if (!costmap->worldToMapContinuous(
goal.pose.position.x,
goal.pose.position.y,
mx_goal,
my_goal))
{
throw nav2_core::GoalOutsideMapBounds(
"Goal Coordinates of(" + std::to_string(goal.pose.position.x) + ", " +
std::to_string(goal.pose.position.y) + ") was outside bounds");
}
_a_star->setGoal(mx_goal, my_goal, 0);
// Setup message
nav_msgs::msg::Path plan;
plan.header.stamp = _clock->now();
plan.header.frame_id = _global_frame;
geometry_msgs::msg::PoseStamped pose;
pose.header = plan.header;
pose.pose.position.z = 0.0;
pose.pose.orientation.x = 0.0;
pose.pose.orientation.y = 0.0;
pose.pose.orientation.z = 0.0;
pose.pose.orientation.w = 1.0;
// Corner case of start and goal being on the same cell
if (std::floor(mx_start) == std::floor(mx_goal) && std::floor(my_start) == std::floor(my_goal)) {
pose.pose = start.pose;
// if we have a different start and goal orientation, set the unique path pose to the goal
// orientation, unless use_final_approach_orientation=true where we need it to be the start
// orientation to avoid movement from the local planner
if (start.pose.orientation != goal.pose.orientation && !_use_final_approach_orientation) {
pose.pose.orientation = goal.pose.orientation;
}
plan.poses.push_back(pose);
// Publish raw path for debug
if (_raw_plan_publisher->get_subscription_count() > 0) {
_raw_plan_publisher->publish(plan);
}
return plan;
}
// Compute plan
Node2D::CoordinateVector path;
int num_iterations = 0;
// Note: All exceptions thrown are handled by the planner server and returned to the action
if (!_a_star->createPath(
path, num_iterations,
_tolerance / static_cast<float>(costmap->getResolution()), cancel_checker))
{
// Note: If the start is blocked only one iteration will occur before failure
if (num_iterations == 1) {
throw nav2_core::StartOccupied("Start occupied");
}
if (num_iterations < _a_star->getMaxIterations()) {
throw nav2_core::NoValidPathCouldBeFound("no valid path found");
} else {
throw nav2_core::PlannerTimedOut("exceeded maximum iterations");
}
}
// Convert to world coordinates
plan.poses.reserve(path.size());
for (int i = path.size() - 1; i >= 0; --i) {
pose.pose = getWorldCoords(path[i].x, path[i].y, costmap);
plan.poses.push_back(pose);
}
// Publish raw path for debug
if (_raw_plan_publisher->get_subscription_count() > 0) {
_raw_plan_publisher->publish(plan);
}
// Find how much time we have left to do smoothing
steady_clock::time_point b = steady_clock::now();
duration<double> time_span = duration_cast<duration<double>>(b - a);
double time_remaining = _max_planning_time - static_cast<double>(time_span.count());
#ifdef BENCHMARK_TESTING
std::cout << "It took " << time_span.count() * 1000 <<
" milliseconds with " << num_iterations << " iterations." << std::endl;
#endif
// Smooth plan
_smoother->smooth(plan, costmap, time_remaining);
// If use_final_approach_orientation=true, interpolate the last pose orientation from the
// previous pose to set the orientation to the 'final approach' orientation of the robot so
// it does not rotate.
// And deal with corner case of plan of length 1
// If use_final_approach_orientation=false (default), override last pose orientation to match goal
size_t plan_size = plan.poses.size();
if (_use_final_approach_orientation) {
if (plan_size == 1) {
plan.poses.back().pose.orientation = start.pose.orientation;
} else if (plan_size > 1) {
double dx, dy, theta;
auto last_pose = plan.poses.back().pose.position;
auto approach_pose = plan.poses[plan_size - 2].pose.position;
dx = last_pose.x - approach_pose.x;
dy = last_pose.y - approach_pose.y;
theta = atan2(dy, dx);
plan.poses.back().pose.orientation =
nav2_util::geometry_utils::orientationAroundZAxis(theta);
}
} else if (plan_size > 0) {
plan.poses.back().pose.orientation = goal.pose.orientation;
}
return plan;
}
rcl_interfaces::msg::SetParametersResult
SmacPlanner2D::dynamicParametersCallback(std::vector<rclcpp::Parameter> parameters)
{
rcl_interfaces::msg::SetParametersResult result;
std::lock_guard<std::mutex> lock_reinit(_mutex);
bool reinit_a_star = false;
bool reinit_downsampler = false;
for (auto parameter : parameters) {
const auto & param_type = parameter.get_type();
const auto & param_name = parameter.get_name();
if(param_name.find(_name + ".") != 0) {
continue;
}
if (param_type == ParameterType::PARAMETER_DOUBLE) {
if (param_name == _name + ".tolerance") {
_tolerance = static_cast<float>(parameter.as_double());
} else if (param_name == _name + ".cost_travel_multiplier") {
reinit_a_star = true;
_search_info.cost_penalty = parameter.as_double();
} else if (param_name == _name + ".max_planning_time") {
reinit_a_star = true;
_max_planning_time = parameter.as_double();
}
} else if (param_type == ParameterType::PARAMETER_BOOL) {
if (param_name == _name + ".downsample_costmap") {
reinit_downsampler = true;
_downsample_costmap = parameter.as_bool();
} else if (param_name == _name + ".allow_unknown") {
reinit_a_star = true;
_allow_unknown = parameter.as_bool();
} else if (param_name == _name + ".use_final_approach_orientation") {
_use_final_approach_orientation = parameter.as_bool();
}
} else if (param_type == ParameterType::PARAMETER_INTEGER) {
if (param_name == _name + ".downsampling_factor") {
reinit_downsampler = true;
_downsampling_factor = parameter.as_int();
} else if (param_name == _name + ".max_iterations") {
reinit_a_star = true;
_max_iterations = parameter.as_int();
if (_max_iterations <= 0) {
RCLCPP_INFO(
_logger, "maximum iteration selected as <= 0, "
"disabling maximum iterations.");
_max_iterations = std::numeric_limits<int>::max();
}
} else if (param_name == _name + ".max_on_approach_iterations") {
reinit_a_star = true;
_max_on_approach_iterations = parameter.as_int();
if (_max_on_approach_iterations <= 0) {
RCLCPP_INFO(
_logger, "On approach iteration selected as <= 0, "
"disabling tolerance and on approach iterations.");
_max_on_approach_iterations = std::numeric_limits<int>::max();
}
} else if (param_name == _name + ".terminal_checking_interval") {
reinit_a_star = true;
_terminal_checking_interval = parameter.as_int();
}
}
}
// Re-init if needed with mutex lock (to avoid re-init while creating a plan)
if (reinit_a_star || reinit_downsampler) {
// Re-Initialize A* template
if (reinit_a_star) {
_a_star = std::make_unique<AStarAlgorithm<Node2D>>(_motion_model, _search_info);
_a_star->initialize(
_allow_unknown,
_max_iterations,
_max_on_approach_iterations,
_terminal_checking_interval,
_max_planning_time,
0.0 /*unused for 2D*/,
1.0 /*unused for 2D*/);
}
// Re-Initialize costmap downsampler
if (reinit_downsampler) {
if (_downsample_costmap && _downsampling_factor > 1) {
auto node = _node.lock();
std::string topic_name = "downsampled_costmap";
_costmap_downsampler = std::make_unique<CostmapDownsampler>();
_costmap_downsampler->on_configure(
node, _global_frame, topic_name, _costmap, _downsampling_factor);
}
}
}
result.successful = true;
return result;
}
} // namespace nav2_smac_planner
#include "pluginlib/class_list_macros.hpp"
PLUGINLIB_EXPORT_CLASS(nav2_smac_planner::SmacPlanner2D, nav2_core::GlobalPlanner)