forked from autowarefoundation/autoware.universe
-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathutilities.cpp
1749 lines (1538 loc) · 63.4 KB
/
utilities.cpp
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 Tier IV, Inc.
//
// 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.
#include "behavior_path_planner/utilities.hpp"
#include <lanelet2_extension/utility/message_conversion.hpp>
#include <lanelet2_extension/utility/query.hpp>
#include <lanelet2_extension/utility/utilities.hpp>
#include <opencv2/opencv.hpp>
#include <tier4_autoware_utils/tier4_autoware_utils.hpp>
#include <algorithm>
#include <limits>
#include <memory>
#include <string>
#include <vector>
namespace drivable_area_utils
{
double quantize(const double val, const double resolution)
{
return std::round(val / resolution) * resolution;
}
void updateMinMaxPosition(
const Eigen::Vector2d & point, boost::optional<double> & min_x, boost::optional<double> & min_y,
boost::optional<double> & max_x, boost::optional<double> & max_y)
{
min_x = min_x ? std::min(min_x.get(), point.x()) : point.x();
min_y = min_y ? std::min(min_y.get(), point.y()) : point.y();
max_x = max_x ? std::max(max_x.get(), point.x()) : point.x();
max_y = max_y ? std::max(max_y.get(), point.y()) : point.y();
}
bool sumLengthFromTwoPoints(
const Eigen::Vector2d & base_point, const Eigen::Vector2d & target_point,
const double length_threshold, double & sum_length, boost::optional<double> & min_x,
boost::optional<double> & min_y, boost::optional<double> & max_x, boost::optional<double> & max_y)
{
const double norm_length = (base_point - target_point).norm();
sum_length += norm_length;
if (length_threshold < sum_length) {
const double diff_length = norm_length - (sum_length - length_threshold);
const Eigen::Vector2d interpolated_point =
base_point + diff_length * (target_point - base_point).normalized();
updateMinMaxPosition(interpolated_point, min_x, min_y, max_x, max_y);
const bool is_end = true;
return is_end;
}
updateMinMaxPosition(target_point, min_x, min_y, max_x, max_y);
const bool is_end = false;
return is_end;
}
std::array<double, 4> getLaneletScope(
const lanelet::ConstLanelets & lanes, const size_t nearest_lane_idx,
const geometry_msgs::msg::Pose & current_pose, const double forward_lane_length,
const double backward_lane_length, const double lane_margin)
{
// define functions to get right/left bounds as a vector
const auto get_bound_funcs =
std::vector<std::function<lanelet::ConstLineString2d(const lanelet::ConstLanelet & lane)>>{
[](const lanelet::ConstLanelet & lane) -> lanelet::ConstLineString2d {
return lane.rightBound2d();
},
[](const lanelet::ConstLanelet & lane) -> lanelet::ConstLineString2d {
return lane.leftBound2d();
}};
// calculate min/max x and y
boost::optional<double> min_x;
boost::optional<double> min_y;
boost::optional<double> max_x;
boost::optional<double> max_y;
for (const auto & get_bound_func : get_bound_funcs) {
// search nearest point index to current pose
const auto & nearest_bound = get_bound_func(lanes.at(nearest_lane_idx));
if (nearest_bound.empty()) {
continue;
}
std::vector<geometry_msgs::msg::Point> points;
for (const auto & point : nearest_bound) {
geometry_msgs::msg::Point p;
p.x = point.x();
p.y = point.y();
points.push_back(p);
}
const size_t nearest_segment_idx =
tier4_autoware_utils::findNearestSegmentIndex(points, current_pose.position);
// forward lanelet
const auto forward_offset_length =
tier4_autoware_utils::calcSignedArcLength(points, current_pose.position, nearest_segment_idx);
double sum_length = std::min(forward_offset_length, 0.0);
size_t current_lane_idx = nearest_lane_idx;
auto current_lane = lanes.at(current_lane_idx);
size_t current_point_idx = nearest_segment_idx;
while (true) {
const auto & bound = get_bound_func(current_lane);
if (current_point_idx != bound.size() - 1) {
const Eigen::Vector2d & current_point = bound[current_point_idx].basicPoint();
const Eigen::Vector2d & next_point = bound[current_point_idx + 1].basicPoint();
const bool is_end_lane = drivable_area_utils::sumLengthFromTwoPoints(
current_point, next_point, forward_lane_length + lane_margin, sum_length, min_x, min_y,
max_x, max_y);
if (is_end_lane) {
break;
}
++current_point_idx;
} else {
const auto previous_lane = current_lane;
const size_t previous_point_idx = get_bound_func(previous_lane).size() - 1;
const auto & previous_bound = get_bound_func(previous_lane);
drivable_area_utils::updateMinMaxPosition(
previous_bound[previous_point_idx].basicPoint(), min_x, min_y, max_x, max_y);
if (current_lane_idx == lanes.size() - 1) {
break;
}
current_lane_idx += 1;
current_lane = lanes.at(current_lane_idx);
current_point_idx = 0;
const auto & current_bound = get_bound_func(current_lane);
const Eigen::Vector2d & prev_point = previous_bound[previous_point_idx].basicPoint();
const Eigen::Vector2d & current_point = current_bound[current_point_idx].basicPoint();
const bool is_end_lane = drivable_area_utils::sumLengthFromTwoPoints(
prev_point, current_point, forward_lane_length + lane_margin, sum_length, min_x, min_y,
max_x, max_y);
if (is_end_lane) {
break;
}
}
}
// backward lanelet
current_point_idx = nearest_segment_idx + 1;
const auto backward_offset_length = tier4_autoware_utils::calcSignedArcLength(
points, nearest_segment_idx + 1, current_pose.position);
sum_length = std::min(backward_offset_length, 0.0);
current_lane_idx = nearest_lane_idx;
current_lane = lanes.at(current_lane_idx);
while (true) {
const auto & bound = get_bound_func(current_lane);
if (current_point_idx != 0) {
const Eigen::Vector2d & current_point = bound[current_point_idx].basicPoint();
const Eigen::Vector2d & prev_point = bound[current_point_idx - 1].basicPoint();
const bool is_end_lane = drivable_area_utils::sumLengthFromTwoPoints(
current_point, prev_point, backward_lane_length + lane_margin, sum_length, min_x, min_y,
max_x, max_y);
if (is_end_lane) {
break;
}
--current_point_idx;
} else {
const auto next_lane = current_lane;
const size_t next_point_idx = 0;
const auto & next_bound = get_bound_func(next_lane);
drivable_area_utils::updateMinMaxPosition(
next_bound[next_point_idx].basicPoint(), min_x, min_y, max_x, max_y);
if (current_lane_idx == 0) {
break;
}
current_lane_idx -= 1;
current_lane = lanes.at(current_lane_idx);
const auto & current_bound = get_bound_func(current_lane);
current_point_idx = current_bound.size() - 1;
const Eigen::Vector2d & next_point = next_bound[next_point_idx].basicPoint();
const Eigen::Vector2d & current_point = current_bound[current_point_idx].basicPoint();
const bool is_end_lane = drivable_area_utils::sumLengthFromTwoPoints(
next_point, current_point, backward_lane_length + lane_margin, sum_length, min_x, min_y,
max_x, max_y);
if (is_end_lane) {
break;
}
}
}
}
if (!min_x || !min_y || !max_x || !max_y) {
const double x = current_pose.position.x;
const double y = current_pose.position.y;
return {x, y, x, y};
}
return {min_x.get(), min_y.get(), max_x.get(), max_y.get()};
}
} // namespace drivable_area_utils
namespace behavior_path_planner
{
namespace util
{
using autoware_auto_perception_msgs::msg::ObjectClassification;
using autoware_auto_perception_msgs::msg::Shape;
using geometry_msgs::msg::PoseWithCovarianceStamped;
std::vector<Point> convertToPointArray(const PathWithLaneId & path)
{
std::vector<Point> point_array;
for (const auto & pt : path.points) {
point_array.push_back(pt.point.pose.position);
}
return point_array;
}
double l2Norm(const Vector3 vector)
{
return std::sqrt(std::pow(vector.x, 2) + std::pow(vector.y, 2) + std::pow(vector.z, 2));
}
FrenetCoordinate3d convertToFrenetCoordinate3d(
const std::vector<Pose> & linestring, const Pose & search_point_geom)
{
FrenetCoordinate3d frenet_coordinate;
const size_t nearest_segment_idx = [&]() {
const auto opt_nearest =
tier4_autoware_utils::findNearestSegmentIndex(linestring, search_point_geom, 3.0, 1.57);
if (opt_nearest) {
return opt_nearest.get();
}
return tier4_autoware_utils::findNearestSegmentIndex(linestring, search_point_geom.position);
}();
const double longitudinal_length = tier4_autoware_utils::calcLongitudinalOffsetToSegment(
linestring, nearest_segment_idx, search_point_geom.position);
frenet_coordinate.length =
tier4_autoware_utils::calcSignedArcLength(linestring, 0, nearest_segment_idx) +
longitudinal_length;
frenet_coordinate.distance = tier4_autoware_utils::calcLateralOffset(
linestring, search_point_geom.position, nearest_segment_idx);
return frenet_coordinate;
}
std::vector<Pose> convertToGeometryPoseVector(const PathWithLaneId & path)
{
std::vector<Pose> converted_path;
converted_path.reserve(path.points.size());
for (const auto & point_with_id : path.points) {
converted_path.push_back(point_with_id.point.pose);
}
return converted_path;
}
FrenetCoordinate3d convertToFrenetCoordinate3d(
const PathWithLaneId & path, const Pose & search_point_geom)
{
const auto linestring = convertToGeometryPoseVector(path);
return convertToFrenetCoordinate3d(linestring, search_point_geom);
}
std::vector<Point> convertToGeometryPointArray(const PathWithLaneId & path)
{
std::vector<Point> converted_path;
converted_path.reserve(path.points.size());
for (const auto & point_with_id : path.points) {
converted_path.push_back(point_with_id.point.pose.position);
}
return converted_path;
}
std::vector<Point> convertToGeometryPointArray(const PredictedPath & path)
{
std::vector<Point> converted_path;
converted_path.reserve(path.path.size());
for (const auto & pose : path.path) {
converted_path.push_back(pose.position);
}
return converted_path;
}
PoseArray convertToGeometryPoseArray(const PathWithLaneId & path)
{
PoseArray converted_array;
converted_array.header = path.header;
converted_array.poses.reserve(path.points.size());
for (const auto & point_with_id : path.points) {
converted_array.poses.push_back(point_with_id.point.pose);
}
return converted_array;
}
PredictedPath convertToPredictedPath(
const PathWithLaneId & path, const Twist & vehicle_twist, const Pose & vehicle_pose,
const double duration, const double resolution, const double acceleration)
{
PredictedPath predicted_path{};
predicted_path.time_step = rclcpp::Duration::from_seconds(resolution);
predicted_path.path.reserve(std::min(path.points.size(), static_cast<size_t>(100)));
if (path.points.empty()) {
return predicted_path;
}
const auto & geometry_pose_vec = convertToGeometryPoseVector(path);
const auto & geometry_points = convertToGeometryPointArray(path);
FrenetCoordinate3d vehicle_pose_frenet =
convertToFrenetCoordinate3d(geometry_pose_vec, vehicle_pose);
auto clock{rclcpp::Clock{RCL_ROS_TIME}};
rclcpp::Time start_time = clock.now();
double vehicle_speed = std::abs(vehicle_twist.linear.x);
constexpr double min_speed = 1.0;
if (vehicle_speed < min_speed) {
vehicle_speed = min_speed;
RCLCPP_DEBUG_STREAM_THROTTLE(
rclcpp::get_logger("behavior_path_planner").get_child("utilities"), clock, 1000,
"cannot convert PathWithLaneId with zero velocity, using minimum value " << min_speed
<< " [m/s] instead");
}
double length = 0;
double prev_vehicle_speed = vehicle_speed;
// first point
const auto pt = lerpByLength(geometry_points, vehicle_pose_frenet.length);
Pose predicted_pose;
predicted_pose.position = pt;
predicted_path.path.push_back(predicted_pose);
for (double t = resolution; t < duration; t += resolution) {
double accelerated_velocity = prev_vehicle_speed + acceleration * t;
double travel_distance = 0;
if (accelerated_velocity < min_speed) {
travel_distance = min_speed * resolution;
} else {
travel_distance =
prev_vehicle_speed * resolution + 0.5 * acceleration * resolution * resolution;
}
length += travel_distance;
const auto pt = lerpByLength(geometry_points, vehicle_pose_frenet.length + length);
Pose predicted_pose;
predicted_pose.position = pt;
predicted_path.path.push_back(predicted_pose);
prev_vehicle_speed = accelerated_velocity;
}
return predicted_path;
}
PredictedPath resamplePredictedPath(
const PredictedPath & input_path, const double resolution, const double duration)
{
PredictedPath resampled_path{};
for (double t = 0.0; t < duration; t += resolution) {
Pose pose;
if (!lerpByTimeStamp(input_path, t, &pose)) {
continue;
}
resampled_path.path.push_back(pose);
}
return resampled_path;
}
Pose lerpByPose(const Pose & p1, const Pose & p2, const double t)
{
tf2::Transform tf_transform1, tf_transform2;
tf2::fromMsg(p1, tf_transform1);
tf2::fromMsg(p2, tf_transform2);
const auto & tf_point = tf2::lerp(tf_transform1.getOrigin(), tf_transform2.getOrigin(), t);
const auto & tf_quaternion =
tf2::slerp(tf_transform1.getRotation(), tf_transform2.getRotation(), t);
Pose pose{};
pose.position = tf2::toMsg(tf_point, pose.position);
pose.orientation = tf2::toMsg(tf_quaternion);
return pose;
}
Point lerpByPoint(const Point & p1, const Point & p2, const double t)
{
tf2::Vector3 v1, v2;
v1.setValue(p1.x, p1.y, p1.z);
v2.setValue(p2.x, p2.y, p2.z);
const auto lerped_point = v1.lerp(v2, t);
Point point;
point.x = lerped_point.x();
point.y = lerped_point.y();
point.z = lerped_point.z();
return point;
}
Point lerpByLength(const std::vector<Point> & point_array, const double length)
{
Point lerped_point;
if (point_array.empty()) {
return lerped_point;
}
Point prev_pt = point_array.front();
double accumulated_length = 0;
for (const auto & pt : point_array) {
const double distance = tier4_autoware_utils::calcDistance3d(prev_pt, pt);
if (accumulated_length + distance > length) {
return lerpByPoint(prev_pt, pt, (length - accumulated_length) / distance);
}
accumulated_length += distance;
prev_pt = pt;
}
return point_array.back();
}
bool lerpByTimeStamp(const PredictedPath & path, const double t_query, Pose * lerped_pt)
{
const rclcpp::Duration time_step(path.time_step);
auto clock{rclcpp::Clock{RCL_ROS_TIME}};
if (lerped_pt == nullptr) {
RCLCPP_WARN_STREAM_THROTTLE(
rclcpp::get_logger("behavior_path_planner").get_child("utilities"), clock, 1000,
"failed to lerp by time due to nullptr pt");
return false;
}
if (path.path.empty()) {
RCLCPP_WARN_STREAM_THROTTLE(
rclcpp::get_logger("behavior_path_planner").get_child("utilities"), clock, 1000,
"Empty path. Failed to interpolate path by time!");
return false;
}
const double t_final = time_step.seconds() * static_cast<double>(path.path.size() - 1);
if (t_query > t_final) {
RCLCPP_DEBUG_STREAM(
rclcpp::get_logger("behavior_path_planner").get_child("utilities"),
"failed to interpolate path by time!" << std::endl
<< "t_final : " << t_final
<< "query time : " << t_query);
*lerped_pt = path.path.back();
return false;
}
for (size_t i = 1; i < path.path.size(); i++) {
const auto & pt = path.path.at(i);
const auto & prev_pt = path.path.at(i - 1);
const double t = time_step.seconds() * static_cast<double>(i);
if (t_query <= t) {
const double prev_t = time_step.seconds() * static_cast<double>(i - 1);
const double duration = time_step.seconds();
const double offset = t_query - prev_t;
const double ratio = offset / duration;
*lerped_pt = lerpByPose(prev_pt, pt, ratio);
return true;
}
}
RCLCPP_ERROR_STREAM(
rclcpp::get_logger("behavior_path_planner").get_child("utilities"),
"Something failed in function: ");
return false;
}
bool lerpByDistance(
const behavior_path_planner::PullOutPath & path, const double & s, Pose * lerped_pt,
const lanelet::ConstLanelets & road_lanes)
{
if (lerped_pt == nullptr) {
// ROS_WARN_STREAM_THROTTLE(1, "failed to lerp by distance due to nullptr pt");
return false;
}
for (size_t i = 1; i < path.path.points.size(); i++) {
const auto & pt = path.path.points.at(i).point.pose;
const auto & prev_pt = path.path.points.at(i - 1).point.pose;
if (
(s >= lanelet::utils::getArcCoordinates(road_lanes, prev_pt).length) &&
(s < lanelet::utils::getArcCoordinates(road_lanes, pt).length)) {
const double distance = lanelet::utils::getArcCoordinates(road_lanes, pt).length -
lanelet::utils::getArcCoordinates(road_lanes, prev_pt).length;
const auto offset = s - lanelet::utils::getArcCoordinates(road_lanes, prev_pt).length;
const auto ratio = offset / distance;
*lerped_pt = lerpByPose(prev_pt, pt, ratio);
return true;
}
}
// ROS_ERROR_STREAM("Something failed in function: " << __func__);
return false;
}
double getDistanceBetweenPredictedPaths(
const PredictedPath & object_path, const PredictedPath & ego_path, const double start_time,
const double end_time, const double resolution)
{
double min_distance = std::numeric_limits<double>::max();
const auto ego_path_point_array = convertToGeometryPointArray(ego_path);
for (double t = start_time; t < end_time; t += resolution) {
Pose object_pose, ego_pose;
if (!lerpByTimeStamp(object_path, t, &object_pose)) {
continue;
}
if (!lerpByTimeStamp(ego_path, t, &ego_pose)) {
continue;
}
double distance = tier4_autoware_utils::calcDistance3d(object_pose, ego_pose);
if (distance < min_distance) {
min_distance = distance;
}
}
return min_distance;
}
double getDistanceBetweenPredictedPathAndObject(
const PredictedObject & object, const PredictedPath & ego_path, const double start_time,
const double end_time, const double resolution)
{
auto clock{rclcpp::Clock{RCL_ROS_TIME}};
auto t_delta{rclcpp::Duration::from_seconds(resolution)};
double min_distance = std::numeric_limits<double>::max();
rclcpp::Time ros_start_time = clock.now() + rclcpp::Duration::from_seconds(start_time);
rclcpp::Time ros_end_time = clock.now() + rclcpp::Duration::from_seconds(end_time);
const auto ego_path_point_array = convertToGeometryPointArray(ego_path);
Polygon2d obj_polygon;
if (!calcObjectPolygon(object, &obj_polygon)) {
return min_distance;
}
for (double t = start_time; t < end_time; t += resolution) {
Pose ego_pose;
if (!lerpByTimeStamp(ego_path, t, &ego_pose)) {
continue;
}
Point2d ego_point{ego_pose.position.x, ego_pose.position.y};
double distance = boost::geometry::distance(obj_polygon, ego_point);
if (distance < min_distance) {
min_distance = distance;
}
}
return min_distance;
}
double getDistanceBetweenPredictedPathAndObjectPolygon(
const PredictedObject & object, const PullOutPath & ego_path,
const tier4_autoware_utils::LinearRing2d & vehicle_footprint, double distance_resolution,
const lanelet::ConstLanelets & road_lanes)
{
double min_distance = std::numeric_limits<double>::max();
const auto ego_path_point_array = convertToGeometryPointArray(ego_path.path);
Polygon2d obj_polygon;
if (!calcObjectPolygon(object, &obj_polygon)) {
// ROS_ERROR("calcObjectPolygon failed");
return min_distance;
}
const auto s_start =
lanelet::utils::getArcCoordinates(road_lanes, ego_path.path.points.front().point.pose).length;
const auto s_end = lanelet::utils::getArcCoordinates(road_lanes, ego_path.shift_point.end).length;
for (auto s = s_start + distance_resolution; s < s_end; s += distance_resolution) {
Pose ego_pose;
if (!lerpByDistance(ego_path, s, &ego_pose, road_lanes)) {
// ROS_ERROR("lerp failed");
continue;
}
const auto vehicle_footprint_on_path =
transformVector(vehicle_footprint, tier4_autoware_utils::pose2transform(ego_pose));
Point2d ego_point{ego_pose.position.x, ego_pose.position.y};
for (const auto & vehicle_footprint : vehicle_footprint_on_path) {
double distance = boost::geometry::distance(obj_polygon, vehicle_footprint);
if (distance < min_distance) {
min_distance = distance;
}
}
}
return min_distance;
}
// only works with consecutive lanes
std::vector<size_t> filterObjectsByLanelets(
const PredictedObjects & objects, const lanelet::ConstLanelets & target_lanelets,
const double start_arc_length, const double end_arc_length)
{
std::vector<size_t> indices;
if (target_lanelets.empty()) {
return {};
}
const auto polygon =
lanelet::utils::getPolygonFromArcLength(target_lanelets, start_arc_length, end_arc_length);
const auto polygon2d = lanelet::utils::to2D(polygon).basicPolygon();
if (polygon2d.empty()) {
// no lanelet polygon
return {};
}
for (size_t i = 0; i < objects.objects.size(); i++) {
const auto obj = objects.objects.at(i);
// create object polygon
Polygon2d obj_polygon;
if (!calcObjectPolygon(obj, &obj_polygon)) {
continue;
}
// create lanelet polygon
Polygon2d lanelet_polygon;
for (const auto & lanelet_point : polygon2d) {
lanelet_polygon.outer().emplace_back(lanelet_point.x(), lanelet_point.y());
}
lanelet_polygon.outer().push_back(lanelet_polygon.outer().front());
// check the object does not intersect the lanelet
if (!boost::geometry::disjoint(lanelet_polygon, obj_polygon)) {
indices.push_back(i);
continue;
}
}
return indices;
}
// works with random lanelets
std::vector<size_t> filterObjectsByLanelets(
const PredictedObjects & objects, const lanelet::ConstLanelets & target_lanelets)
{
std::vector<size_t> indices;
if (target_lanelets.empty()) {
return {};
}
for (size_t i = 0; i < objects.objects.size(); i++) {
// create object polygon
const auto obj = objects.objects.at(i);
// create object polygon
Polygon2d obj_polygon;
if (!calcObjectPolygon(obj, &obj_polygon)) {
RCLCPP_ERROR_STREAM(
rclcpp::get_logger("behavior_path_planner").get_child("utilities"),
"Failed to calcObjectPolygon...!!!");
continue;
}
for (const auto & llt : target_lanelets) {
// create lanelet polygon
const auto polygon2d = llt.polygon2d().basicPolygon();
if (polygon2d.empty()) {
// no lanelet polygon
continue;
}
Polygon2d lanelet_polygon;
for (const auto & lanelet_point : polygon2d) {
lanelet_polygon.outer().emplace_back(lanelet_point.x(), lanelet_point.y());
}
lanelet_polygon.outer().push_back(lanelet_polygon.outer().front());
// check the object does not intersect the lanelet
if (!boost::geometry::disjoint(lanelet_polygon, obj_polygon)) {
indices.push_back(i);
break;
}
}
}
return indices;
}
bool calcObjectPolygon(const PredictedObject & object, Polygon2d * object_polygon)
{
const double obj_x = object.kinematics.initial_pose_with_covariance.pose.position.x;
const double obj_y = object.kinematics.initial_pose_with_covariance.pose.position.y;
if (object.shape.type == Shape::BOUNDING_BOX) {
const double len_x = object.shape.dimensions.x;
const double len_y = object.shape.dimensions.y;
tf2::Transform tf_map2obj;
tf2::fromMsg(object.kinematics.initial_pose_with_covariance.pose, tf_map2obj);
// set vertices at map coordinate
tf2::Vector3 p1_map, p2_map, p3_map, p4_map;
p1_map.setX(len_x / 2);
p1_map.setY(len_y / 2);
p1_map.setZ(0.0);
p1_map.setW(1.0);
p2_map.setX(-len_x / 2);
p2_map.setY(len_y / 2);
p2_map.setZ(0.0);
p2_map.setW(1.0);
p3_map.setX(-len_x / 2);
p3_map.setY(-len_y / 2);
p3_map.setZ(0.0);
p3_map.setW(1.0);
p4_map.setX(len_x / 2);
p4_map.setY(-len_y / 2);
p4_map.setZ(0.0);
p4_map.setW(1.0);
// transform vertices from map coordinate to object coordinate
tf2::Vector3 p1_obj, p2_obj, p3_obj, p4_obj;
p1_obj = tf_map2obj * p1_map;
p2_obj = tf_map2obj * p2_map;
p3_obj = tf_map2obj * p3_map;
p4_obj = tf_map2obj * p4_map;
object_polygon->outer().emplace_back(p1_obj.x(), p1_obj.y());
object_polygon->outer().emplace_back(p2_obj.x(), p2_obj.y());
object_polygon->outer().emplace_back(p3_obj.x(), p3_obj.y());
object_polygon->outer().emplace_back(p4_obj.x(), p4_obj.y());
} else if (object.shape.type == Shape::CYLINDER) {
const size_t N = 20;
const double r = object.shape.dimensions.x / 2;
for (size_t i = 0; i < N; ++i) {
object_polygon->outer().emplace_back(
obj_x + r * std::cos(2.0 * M_PI / N * i), obj_y + r * std::sin(2.0 * M_PI / N * i));
}
} else if (object.shape.type == Shape::POLYGON) {
tf2::Transform tf_map2obj;
tf2::fromMsg(object.kinematics.initial_pose_with_covariance.pose, tf_map2obj);
const auto obj_points = object.shape.footprint.points;
for (const auto & obj_point : obj_points) {
tf2::Vector3 obj(obj_point.x, obj_point.y, obj_point.z);
tf2::Vector3 tf_obj = tf_map2obj * obj;
object_polygon->outer().emplace_back(tf_obj.x(), tf_obj.y());
}
} else {
RCLCPP_WARN(
rclcpp::get_logger("behavior_path_planner").get_child("utilities"), "Object shape unknown!");
return false;
}
object_polygon->outer().push_back(object_polygon->outer().front());
return true;
}
std::vector<double> calcObjectsDistanceToPath(
const PredictedObjects & objects, const PathWithLaneId & ego_path)
{
std::vector<double> distance_array;
const auto ego_path_point_array = convertToGeometryPointArray(ego_path);
for (const auto & obj : objects.objects) {
Polygon2d obj_polygon;
if (!calcObjectPolygon(obj, &obj_polygon)) {
std::cerr << __func__ << ": fail to convert object to polygon" << std::endl;
continue;
}
LineString2d ego_path_line;
for (size_t j = 0; j < ego_path_point_array.size(); ++j) {
boost::geometry::append(
ego_path_line, Point2d(ego_path_point_array.at(j).x, ego_path_point_array.at(j).y));
}
const double distance = boost::geometry::distance(obj_polygon, ego_path_line);
distance_array.push_back(distance);
}
return distance_array;
}
std::vector<size_t> filterObjectsByPath(
const PredictedObjects & objects, const std::vector<size_t> & object_indices,
const PathWithLaneId & ego_path, const double vehicle_width)
{
std::vector<size_t> indices;
const auto ego_path_point_array = convertToGeometryPointArray(ego_path);
for (const auto & i : object_indices) {
Polygon2d obj_polygon;
if (!calcObjectPolygon(objects.objects.at(i), &obj_polygon)) {
continue;
}
LineString2d ego_path_line;
for (size_t j = 0; j < ego_path_point_array.size(); ++j) {
boost::geometry::append(
ego_path_line, Point2d(ego_path_point_array.at(j).x, ego_path_point_array.at(j).y));
}
const double distance = boost::geometry::distance(obj_polygon, ego_path_line);
if (distance < vehicle_width) {
indices.push_back(i);
}
}
return indices;
}
PathWithLaneId removeOverlappingPoints(const PathWithLaneId & input_path)
{
PathWithLaneId filtered_path;
for (const auto & pt : input_path.points) {
if (filtered_path.points.empty()) {
filtered_path.points.push_back(pt);
continue;
}
constexpr double min_dist = 0.001;
if (
tier4_autoware_utils::calcDistance3d(filtered_path.points.back().point, pt.point) <
min_dist) {
filtered_path.points.back().lane_ids.push_back(pt.lane_ids.front());
filtered_path.points.back().point.longitudinal_velocity_mps = std::min(
pt.point.longitudinal_velocity_mps,
filtered_path.points.back().point.longitudinal_velocity_mps);
} else {
filtered_path.points.push_back(pt);
}
}
filtered_path.drivable_area = input_path.drivable_area;
return filtered_path;
}
template <typename T>
bool exists(std::vector<T> vec, T element)
{
return std::find(vec.begin(), vec.end(), element) != vec.end();
}
boost::optional<size_t> findNearestIndexToGoal(
const std::vector<autoware_auto_planning_msgs::msg::PathPointWithLaneId> & points,
const geometry_msgs::msg::Pose & goal, const int64_t goal_lane_id,
const double max_dist = std::numeric_limits<double>::max())
{
if (points.empty()) {
return boost::none;
}
size_t min_dist_index;
double min_dist = std::numeric_limits<double>::max();
{
bool found = false;
for (size_t i = 0; i < points.size(); ++i) {
const double x = points.at(i).point.pose.position.x - goal.position.x;
const double y = points.at(i).point.pose.position.y - goal.position.y;
const double dist = std::hypot(x, y);
if (dist < max_dist && dist < min_dist && exists(points.at(i).lane_ids, goal_lane_id)) {
min_dist_index = i;
min_dist = dist;
found = true;
}
}
if (!found) {
return boost::none;
}
}
size_t min_dist_out_of_range_index = min_dist_index;
for (size_t i = min_dist_index; i != 0; --i) {
const double x = points.at(i).point.pose.position.x - goal.position.x;
const double y = points.at(i).point.pose.position.y - goal.position.y;
const double dist = std::hypot(x, y);
min_dist_out_of_range_index = i;
if (max_dist < dist) {
break;
}
}
return min_dist_out_of_range_index;
}
// goal does not have z
bool setGoal(
const double search_radius_range, [[maybe_unused]] const double search_rad_range,
const PathWithLaneId & input, const Pose & goal, const int64_t goal_lane_id,
PathWithLaneId * output_ptr)
{
try {
if (input.points.empty()) {
return false;
}
// calculate refined_goal with interpolation
PathPointWithLaneId refined_goal{};
{ // NOTE: goal does not have valid z, that will be calculated by interpolation here
const size_t closest_seg_idx =
tier4_autoware_utils::findNearestSegmentIndex(input.points, goal.position);
const double closest_to_goal_dist = tier4_autoware_utils::calcSignedArcLength(
input.points, input.points.at(closest_seg_idx).point.pose.position,
goal.position); // TODO(murooka) implement calcSignedArcLength(points, idx, point)
const double seg_dist = tier4_autoware_utils::calcSignedArcLength(
input.points, closest_seg_idx, closest_seg_idx + 1);
const double closest_z = input.points.at(closest_seg_idx).point.pose.position.z;
const double next_z = input.points.at(closest_seg_idx + 1).point.pose.position.z;
const double goal_z = std::abs(seg_dist) < 1e-6
? next_z
: closest_z + (next_z - closest_z) * closest_to_goal_dist / seg_dist;
refined_goal.point.pose = goal;
refined_goal.point.pose.position.z = goal_z;
refined_goal.point.longitudinal_velocity_mps = 0.0;
refined_goal.lane_ids = input.points.back().lane_ids;
}
// calculate pre_goal
double roll{};
double pitch{};
double yaw{};
tf2::Quaternion tf2_quaternion(
goal.orientation.x, goal.orientation.y, goal.orientation.z, goal.orientation.w);
tf2::Matrix3x3 tf2_matrix(tf2_quaternion);
tf2_matrix.getRPY(roll, pitch, yaw);
// calculate pre_refined_goal with interpolation
PathPointWithLaneId pre_refined_goal{};
pre_refined_goal.point.pose.position.x = goal.position.x - std::cos(yaw);
pre_refined_goal.point.pose.position.y = goal.position.y - std::sin(yaw);
pre_refined_goal.point.pose.orientation = goal.orientation;
{ // NOTE: interpolate z and velocity of pre_refined_goal
const size_t closest_seg_idx = tier4_autoware_utils::findNearestSegmentIndex(
input.points, pre_refined_goal.point.pose.position);
const double closest_to_pre_goal_dist = tier4_autoware_utils::calcSignedArcLength(
input.points, input.points.at(closest_seg_idx).point.pose.position,
pre_refined_goal.point.pose.position);
const double seg_dist = tier4_autoware_utils::calcSignedArcLength(
input.points, closest_seg_idx,
closest_seg_idx + 1); // TODO(murooka) implement calcSignedArcLength(points, idx, point)
const double closest_z = input.points.at(closest_seg_idx).point.pose.position.z;
const double next_z = input.points.at(closest_seg_idx + 1).point.pose.position.z;
pre_refined_goal.point.pose.position.z =
std::abs(seg_dist) < 1e-06
? next_z
: closest_z + (next_z - closest_z) * closest_to_pre_goal_dist / seg_dist;
const double closest_vel = input.points.at(closest_seg_idx).point.longitudinal_velocity_mps;
const double next_vel = input.points.at(closest_seg_idx + 1).point.longitudinal_velocity_mps;
pre_refined_goal.point.longitudinal_velocity_mps =
std::abs(seg_dist) < 1e-06 ? next_vel : closest_vel;
pre_refined_goal.lane_ids = input.points.back().lane_ids;
}
// find min_dist_index whose distance to goal is shorter than search_radius_range
const auto min_dist_index_opt =
findNearestIndexToGoal(input.points, goal, goal_lane_id, search_radius_range);
if (!min_dist_index_opt) {
return false;
}
const size_t min_dist_index =
min_dist_index_opt.get(); // min_dist_idx point is inside the search_radius_range circle 
// find min_dist_out_of_circle_index whose distance to goal is longer than search_radius_range
size_t min_dist_out_of_circle_index = 0;
{
// NOTE: type of i must be int since i will be -1 even if the condition is 0<=i
for (int i = min_dist_index; 0 <= i; --i) {
const double dist = tier4_autoware_utils::calcDistance2d(input.points.at(i).point, goal);
min_dist_out_of_circle_index = i;
if (search_radius_range < dist) {
break;
}
}
}
for (size_t i = 0; i <= min_dist_out_of_circle_index; ++i) {
output_ptr->points.push_back(input.points.at(i));
}
output_ptr->points.push_back(pre_refined_goal);
output_ptr->points.push_back(refined_goal);
output_ptr->drivable_area = input.drivable_area;
return true;
} catch (std::out_of_range & ex) {
RCLCPP_ERROR_STREAM(
rclcpp::get_logger("behavior_path_planner").get_child("utilities"),
"failed to set goal: " << ex.what());
return false;
}
}
const Pose refineGoal(const Pose & goal, const lanelet::ConstLanelet & goal_lanelet)
{
// return goal;
const auto lanelet_point = lanelet::utils::conversion::toLaneletPoint(goal.position);
const double distance = boost::geometry::distance(
goal_lanelet.polygon2d().basicPolygon(), lanelet::utils::to2D(lanelet_point).basicPoint());
if (distance < std::numeric_limits<double>::epsilon()) {
return goal;
}
const auto segment = lanelet::utils::getClosestSegment(
lanelet::utils::to2D(lanelet_point), goal_lanelet.centerline());
if (segment.empty()) {
return goal;
}
Pose refined_goal;
{
// find position
const auto p1 = segment.front().basicPoint();
const auto p2 = segment.back().basicPoint();