-
-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Expand file tree
/
Copy pathMap.cpp
More file actions
1605 lines (1434 loc) · 60.2 KB
/
Map.cpp
File metadata and controls
1605 lines (1434 loc) · 60.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
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 (c) 2026 Computer Vision Center (CVC) at the Universitat Autonoma
// de Barcelona (UAB).
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
#include "carla/road/Map.h"
#include "carla/Exception.h"
#include "carla/geom/Math.h"
#include "carla/geom/Vector3D.h"
#include "carla/road/MeshFactory.h"
#include "carla/road/Deformation.h"
#include "carla/road/element/LaneCrossingCalculator.h"
#include "carla/road/element/RoadInfoCrosswalk.h"
#include "carla/road/element/RoadInfoElevation.h"
#include "carla/road/element/RoadInfoGeometry.h"
#include "carla/road/element/RoadInfoLaneOffset.h"
#include "carla/road/element/RoadInfoLaneWidth.h"
#include "carla/road/element/RoadInfoMarkRecord.h"
#include "carla/road/element/RoadInfoSpeed.h"
#include "carla/road/element/RoadInfoSignal.h"
#include <third-party/marchingcube/MeshReconstruction.h>
#include <vector>
#include <unordered_map>
#include <stdexcept>
#include <chrono>
#include <thread>
#include <iomanip>
#include <cmath>
namespace carla {
namespace road {
using namespace carla::road::element;
/// We use this epsilon to shift the waypoints away from the edges of the lane
/// sections to avoid floating point precision errors.
static constexpr double EPSILON = 10.0 * std::numeric_limits<double>::epsilon();
// ===========================================================================
// -- Static local methods ---------------------------------------------------
// ===========================================================================
template <typename T>
static std::vector<T> ConcatVectors(std::vector<T> dst, std::vector<T> src) {
if (src.size() > dst.size()) {
return ConcatVectors(src, dst);
}
dst.insert(
dst.end(),
std::make_move_iterator(src.begin()),
std::make_move_iterator(src.end()));
return dst;
}
static double GetDistanceAtStartOfLane(const Lane &lane) {
if (lane.IsPositiveDirection()) {
return lane.GetDistance() + 10.0 * EPSILON;
} else {
return lane.GetDistance() + lane.GetLength() - 10.0 * EPSILON;
}
}
static double GetDistanceAtEndOfLane(const Lane &lane) {
if (!lane.IsPositiveDirection()) {
return lane.GetDistance() + 10.0 * EPSILON;
} else {
return lane.GetDistance() + lane.GetLength() - 10.0 * EPSILON;
}
}
/// Return a waypoint for each drivable lane on @a lane_section.
template <typename FuncT>
static void ForEachDrivableLaneImpl(
RoadId road_id,
const LaneSection &lane_section,
double distance,
FuncT &&func) {
for (const auto &pair : lane_section.GetLanes()) {
const auto &lane = pair.second;
if (lane.GetId() == 0) {
continue;
}
if ((static_cast<uint32_t>(lane.GetType()) & static_cast<uint32_t>(Lane::LaneType::Driving)) > 0) {
std::forward<FuncT>(func)(Waypoint{
road_id,
lane_section.GetId(),
lane.GetId(),
distance < 0.0 ? GetDistanceAtStartOfLane(lane) : distance});
}
}
}
template <typename FuncT>
static void ForEachLaneImpl(
RoadId road_id,
const LaneSection &lane_section,
double distance,
Lane::LaneType lane_type,
FuncT &&func) {
for (const auto &pair : lane_section.GetLanes()) {
const auto &lane = pair.second;
if (lane.GetId() == 0) {
continue;
}
if ((static_cast<int32_t>(lane.GetType()) & static_cast<int32_t>(lane_type)) > 0) {
std::forward<FuncT>(func)(Waypoint{
road_id,
lane_section.GetId(),
lane.GetId(),
distance < 0.0 ? GetDistanceAtStartOfLane(lane) : distance});
}
}
}
/// Return a waypoint for each drivable lane on each lane section of @a road.
template <typename FuncT>
static void ForEachDrivableLane(const Road &road, FuncT &&func) {
for (const auto &lane_section : road.GetLaneSections()) {
ForEachDrivableLaneImpl(
road.GetId(),
lane_section,
-1.0, // At start of the lane
std::forward<FuncT>(func));
}
}
/// Return a waypoint for each lane of the specified type on each lane section of @a road.
template <typename FuncT>
static void ForEachLane(const Road &road, Lane::LaneType lane_type, FuncT &&func) {
for (const auto &lane_section : road.GetLaneSections()) {
ForEachLaneImpl(
road.GetId(),
lane_section,
-1.0, // At start of the lane
lane_type,
std::forward<FuncT>(func));
}
}
/// Return a waypoint for each drivable lane at @a distance on @a road.
template <typename FuncT>
static void ForEachDrivableLaneAt(const Road &road, double distance, FuncT &&func) {
for (const auto &lane_section : road.GetLaneSectionsAt(distance)) {
ForEachDrivableLaneImpl(
road.GetId(),
lane_section,
distance,
std::forward<FuncT>(func));
}
}
/// Assumes road_id and section_id are valid.
static bool IsLanePresent(const MapData &data, Waypoint waypoint) {
const auto §ion = data.GetRoad(waypoint.road_id).GetLaneSectionById(waypoint.section_id);
return section.ContainsLane(waypoint.lane_id);
}
// ===========================================================================
// -- Map: Geometry ----------------------------------------------------------
// ===========================================================================
std::optional<Waypoint> Map::GetClosestWaypointOnRoad(
const geom::Location &pos,
int32_t lane_type) const {
std::vector<Rtree::TreeElement> query_result =
_rtree.GetNearestNeighboursWithFilter(Rtree::BPoint(pos.x, pos.y, pos.z),
[&](Rtree::TreeElement const &element) {
const Lane &lane = GetLane(element.second.first);
return (lane_type & static_cast<int32_t>(lane.GetType())) > 0;
});
if (query_result.size() == 0) {
return std::optional<Waypoint>{};
}
Rtree::BSegment segment = query_result.front().first;
Rtree::BPoint s1 = segment.first;
Rtree::BPoint s2 = segment.second;
auto distance_to_segment = geom::Math::DistanceSegmentToPoint(pos,
geom::Vector3D(s1.get<0>(), s1.get<1>(), s1.get<2>()),
geom::Vector3D(s2.get<0>(), s2.get<1>(), s2.get<2>()));
Waypoint result_start = query_result.front().second.first;
Waypoint result_end = query_result.front().second.second;
if (GetLane(result_start).IsPositiveDirection()) {
double delta_s = distance_to_segment.first;
double final_s = result_start.s + delta_s;
if (final_s >= result_end.s) {
return result_end;
} else if (delta_s <= 0) {
return result_start;
} else {
return GetNext(result_start, delta_s).front();
}
} else {
double delta_s = distance_to_segment.first;
double final_s = result_start.s - delta_s;
if (final_s <= result_end.s) {
return result_end;
} else if (delta_s <= 0) {
return result_start;
} else {
return GetNext(result_start, delta_s).front();
}
}
}
std::optional<Waypoint> Map::GetWaypoint(
const geom::Location &pos,
int32_t lane_type) const {
std::optional<Waypoint> w = GetClosestWaypointOnRoad(pos, lane_type);
if (!w.has_value()) {
return w;
}
const auto dist = geom::Math::Distance2D(ComputeTransform(*w).location, pos);
const auto lane_width_info = GetLane(*w).GetInfo<RoadInfoLaneWidth>(w->s);
const auto half_lane_width =
lane_width_info->GetPolynomial().Evaluate(w->s) * 0.5;
if (dist < half_lane_width) {
return w;
}
return std::optional<Waypoint>{};
}
std::optional<Waypoint> Map::GetWaypoint(
RoadId road_id,
LaneId lane_id,
float s) const {
// define the waypoint with the known parameters
Waypoint waypoint;
waypoint.road_id = road_id;
waypoint.lane_id = lane_id;
waypoint.s = s;
// check the road
if (!_data.ContainsRoad(waypoint.road_id)) {
return std::optional<Waypoint>{};
}
const Road &road = _data.GetRoad(waypoint.road_id);
// check the 's' distance
if (s < 0.0f || s >= road.GetLength()) {
return std::optional<Waypoint>{};
}
// check the section
bool lane_found = false;
for (auto §ion : road.GetLaneSectionsAt(s)) {
if (section.ContainsLane(lane_id)) {
waypoint.section_id = section.GetId();
lane_found = true;
break;
}
}
// check the lane id
if (!lane_found) {
return std::optional<Waypoint>{};
}
return waypoint;
}
geom::Transform Map::ComputeTransform(Waypoint waypoint) const {
return GetLane(waypoint).ComputeTransform(waypoint.s);
}
// ===========================================================================
// -- Map: Road information --------------------------------------------------
// ===========================================================================
Lane::LaneType Map::GetLaneType(const Waypoint waypoint) const {
return GetLane(waypoint).GetType();
}
double Map::GetLaneWidth(const Waypoint waypoint) const {
const auto s = waypoint.s;
const auto &lane = GetLane(waypoint);
RELEASE_ASSERT(lane.GetRoad() != nullptr);
RELEASE_ASSERT(s <= lane.GetRoad()->GetLength());
const auto lane_width_info = lane.GetInfo<RoadInfoLaneWidth>(s);
RELEASE_ASSERT(lane_width_info != nullptr);
return lane_width_info->GetPolynomial().Evaluate(s);
}
JuncId Map::GetJunctionId(RoadId road_id) const {
return _data.GetRoad(road_id).GetJunctionId();
}
bool Map::IsJunction(RoadId road_id) const {
return _data.GetRoad(road_id).IsJunction();
}
std::pair<const RoadInfoMarkRecord *, const RoadInfoMarkRecord *>
Map::GetMarkRecord(const Waypoint waypoint) const {
// if lane Id is 0, just return a pair of nulls
if (waypoint.lane_id == 0)
return std::make_pair(nullptr, nullptr);
const auto s = waypoint.s;
const auto ¤t_lane = GetLane(waypoint);
RELEASE_ASSERT(current_lane.GetRoad() != nullptr);
RELEASE_ASSERT(s <= current_lane.GetRoad()->GetLength());
const auto inner_lane_id = waypoint.lane_id < 0 ?
waypoint.lane_id + 1 :
waypoint.lane_id - 1;
const auto &inner_lane = current_lane.GetRoad()->GetLaneById(waypoint.section_id, inner_lane_id);
auto current_lane_info = current_lane.GetInfo<RoadInfoMarkRecord>(s);
auto inner_lane_info = inner_lane.GetInfo<RoadInfoMarkRecord>(s);
return std::make_pair(current_lane_info, inner_lane_info);
}
std::vector<Map::SignalSearchData> Map::GetSignalsInDistance(
Waypoint waypoint, double distance, bool stop_at_junction) const {
const auto &lane = GetLane(waypoint);
const bool forward = lane.IsPositiveDirection();
const double signed_distance = forward ? distance : -distance;
const double relative_s = waypoint.s - lane.GetDistance();
const double remaining_lane_length = forward ? lane.GetLength() - relative_s : relative_s;
DEBUG_ASSERT(remaining_lane_length >= 0.0);
auto &road =_data.GetRoad(waypoint.road_id);
std::vector<SignalSearchData> result;
// If after subtracting the distance we are still in the same lane, return
// same waypoint with the extra distance.
if (distance <= remaining_lane_length) {
auto signals = road.GetInfosInRange<RoadInfoSignal>(
waypoint.s, waypoint.s + signed_distance);
for(auto* signal : signals){
double distance_to_signal = 0;
if (lane.IsPositiveDirection()){
distance_to_signal = signal->GetDistance() - waypoint.s;
} else {
distance_to_signal = waypoint.s - signal->GetDistance();
}
// check that the signal affects the waypoint
bool is_valid = false;
for (auto &validity : signal->GetValidities()) {
if (waypoint.lane_id >= validity._from_lane &&
waypoint.lane_id <= validity._to_lane) {
is_valid = true;
break;
}
}
if(!is_valid){
continue;
}
if (distance_to_signal == 0) {
result.emplace_back(SignalSearchData
{signal, waypoint,
distance_to_signal});
} else {
result.emplace_back(SignalSearchData
{signal, GetNext(waypoint, distance_to_signal).front(),
distance_to_signal});
}
}
return result;
}
const double signed_remaining_length = forward ? remaining_lane_length : -remaining_lane_length;
//result = road.GetInfosInRange<RoadInfoSignal>(waypoint.s, waypoint.s + signed_remaining_length);
auto signals = road.GetInfosInRange<RoadInfoSignal>(
waypoint.s, waypoint.s + signed_remaining_length);
for(auto* signal : signals){
double distance_to_signal = 0;
if (lane.IsPositiveDirection()){
distance_to_signal = signal->GetDistance() - waypoint.s;
} else {
distance_to_signal = waypoint.s - signal->GetDistance();
}
// check that the signal affects the waypoint
bool is_valid = false;
for (auto &validity : signal->GetValidities()) {
if (waypoint.lane_id >= validity._from_lane &&
waypoint.lane_id <= validity._to_lane) {
is_valid = true;
break;
}
}
if(!is_valid){
continue;
}
if (distance_to_signal == 0) {
result.emplace_back(SignalSearchData
{signal, waypoint,
distance_to_signal});
} else {
result.emplace_back(SignalSearchData
{signal, GetNext(waypoint, distance_to_signal).front(),
distance_to_signal});
}
}
// If we run out of remaining_lane_length we have to go to the successors.
for (auto &successor : GetSuccessors(waypoint)) {
if(_data.GetRoad(successor.road_id).IsJunction() && stop_at_junction){
continue;
}
auto& sucessor_lane = _data.GetRoad(successor.road_id).
GetLaneByDistance(successor.s, successor.lane_id);
if (GetLane(successor).IsPositiveDirection()) {
successor.s = sucessor_lane.GetDistance();
} else {
successor.s = sucessor_lane.GetDistance() + sucessor_lane.GetLength();
}
auto sucessor_signals = GetSignalsInDistance(
successor, distance - remaining_lane_length, stop_at_junction);
for(auto& signal : sucessor_signals){
signal.accumulated_s += remaining_lane_length;
}
result = ConcatVectors(result, sucessor_signals);
}
return result;
}
std::vector<const element::RoadInfoSignal*>
Map::GetAllSignalReferences() const {
std::vector<const element::RoadInfoSignal*> result;
for (const auto& road_pair : _data.GetRoads()) {
const auto &road = road_pair.second;
auto road_infos = road.GetInfos<element::RoadInfoSignal>();
for(const auto* road_info : road_infos) {
result.push_back(road_info);
}
}
return result;
}
std::vector<LaneMarking> Map::CalculateCrossedLanes(
const geom::Location &origin,
const geom::Location &destination) const {
return LaneCrossingCalculator::Calculate(*this, origin, destination);
}
std::vector<geom::Location> Map::GetAllCrosswalkZones() const {
std::vector<geom::Location> result;
for (const auto &pair : _data.GetRoads()) {
const auto &road = pair.second;
std::vector<const RoadInfoCrosswalk *> crosswalks = road.GetInfos<RoadInfoCrosswalk>();
if (crosswalks.size() > 0) {
for (auto crosswalk : crosswalks) {
// waypoint only at start position
std::vector<geom::Location> points;
Waypoint waypoint;
geom::Transform base;
for (const auto §ion : road.GetLaneSectionsAt(crosswalk->GetS())) {
// get the section with the center lane
for (const auto &lane : section.GetLanes()) {
// is the center line
if (lane.first == 0) {
// get the center point
waypoint.road_id = pair.first;
waypoint.section_id = section.GetId();
waypoint.lane_id = 0;
waypoint.s = crosswalk->GetS();
base = ComputeTransform(waypoint);
}
}
}
// move perpendicular ('t')
geom::Transform pivot = base;
pivot.rotation.yaw -= geom::Math::ToDegrees<float>(static_cast<float>(crosswalk->GetHeading()));
pivot.rotation.yaw -= 90; // move perpendicular to 's' for the lateral offset
geom::Vector3D v(static_cast<float>(crosswalk->GetT()), 0.0f, 0.0f);
pivot.TransformPoint(v);
// restore pivot position and orientation
pivot = base;
pivot.location = v;
pivot.rotation.yaw -= geom::Math::ToDegrees<float>(static_cast<float>(crosswalk->GetHeading()));
// calculate all the corners
for (auto corner : crosswalk->GetPoints()) {
geom::Vector3D v2(
static_cast<float>(corner.u),
static_cast<float>(corner.v),
static_cast<float>(corner.z));
// set the width larger to contact with the sidewalk (in case they have gutter area)
if (corner.u < 0) {
v2.x -= 1.0f;
} else {
v2.x += 1.0f;
}
pivot.TransformPoint(v2);
result.push_back(v2);
}
}
}
}
return result;
}
// ===========================================================================
// -- Map: Waypoint generation -----------------------------------------------
// ===========================================================================
std::vector<Waypoint> Map::GetSuccessors(const Waypoint waypoint) const {
const auto &next_lanes = GetLane(waypoint).GetNextLanes();
std::vector<Waypoint> result;
result.reserve(next_lanes.size());
for (auto *next_lane : next_lanes) {
RELEASE_ASSERT(next_lane != nullptr);
const auto lane_id = next_lane->GetId();
RELEASE_ASSERT(lane_id != 0);
const auto *section = next_lane->GetLaneSection();
RELEASE_ASSERT(section != nullptr);
const auto *road = next_lane->GetRoad();
RELEASE_ASSERT(road != nullptr);
const auto distance = GetDistanceAtStartOfLane(*next_lane);
result.emplace_back(Waypoint{road->GetId(), section->GetId(), lane_id, distance});
}
return result;
}
std::vector<Waypoint> Map::GetPredecessors(const Waypoint waypoint) const {
const auto &prev_lanes = GetLane(waypoint).GetPreviousLanes();
std::vector<Waypoint> result;
result.reserve(prev_lanes.size());
for (auto *next_lane : prev_lanes) {
RELEASE_ASSERT(next_lane != nullptr);
const auto lane_id = next_lane->GetId();
RELEASE_ASSERT(lane_id != 0);
const auto *section = next_lane->GetLaneSection();
RELEASE_ASSERT(section != nullptr);
const auto *road = next_lane->GetRoad();
RELEASE_ASSERT(road != nullptr);
const auto distance = GetDistanceAtEndOfLane(*next_lane);
result.emplace_back(Waypoint{road->GetId(), section->GetId(), lane_id, distance});
}
return result;
}
std::vector<Waypoint> Map::GetNext(
const Waypoint waypoint,
const double distance) const {
RELEASE_ASSERT(distance > 0.0);
if (distance <= EPSILON) {
return {waypoint};
}
const auto &lane = GetLane(waypoint);
const bool forward = lane.IsPositiveDirection();
const double signed_distance = forward ? distance : -distance;
const double relative_s = waypoint.s - lane.GetDistance();
const double remaining_lane_length = forward ? lane.GetLength() - relative_s : relative_s;
DEBUG_ASSERT(remaining_lane_length >= 0.0);
// If after subtracting the distance we are still in the same lane, return
// same waypoint with the extra distance.
if (distance <= remaining_lane_length) {
Waypoint result = waypoint;
result.s += signed_distance;
result.s += forward ? -EPSILON : EPSILON;
RELEASE_ASSERT(result.s > 0.0);
return { result };
}
// If we run out of remaining_lane_length we have to go to the successors.
std::vector<Waypoint> result;
for (const auto &successor : GetSuccessors(waypoint)) {
DEBUG_ASSERT(
successor.road_id != waypoint.road_id ||
successor.section_id != waypoint.section_id ||
successor.lane_id != waypoint.lane_id);
result = ConcatVectors(result, GetNext(successor, distance - remaining_lane_length));
}
return result;
}
std::vector<Waypoint> Map::GetPrevious(
const Waypoint waypoint,
const double distance) const {
RELEASE_ASSERT(distance > 0.0);
if (distance <= EPSILON) {
return {waypoint};
}
const auto &lane = GetLane(waypoint);
const bool forward = !lane.IsPositiveDirection();
const double signed_distance = forward ? distance : -distance;
const double relative_s = waypoint.s - lane.GetDistance();
const double remaining_lane_length = forward ? lane.GetLength() - relative_s : relative_s;
DEBUG_ASSERT(remaining_lane_length >= 0.0);
// If after subtracting the distance we are still in the same lane, return
// same waypoint with the extra distance.
if (distance <= remaining_lane_length) {
Waypoint result = waypoint;
result.s += signed_distance;
result.s += forward ? -EPSILON : EPSILON;
RELEASE_ASSERT(result.s > 0.0);
return { result };
}
// If we run out of remaining_lane_length we have to go to the successors.
std::vector<Waypoint> result;
for (const auto &successor : GetPredecessors(waypoint)) {
DEBUG_ASSERT(
successor.road_id != waypoint.road_id ||
successor.section_id != waypoint.section_id ||
successor.lane_id != waypoint.lane_id);
result = ConcatVectors(result, GetPrevious(successor, distance - remaining_lane_length));
}
return result;
}
std::optional<Waypoint> Map::GetRight(Waypoint waypoint) const {
RELEASE_ASSERT(waypoint.lane_id != 0);
bool is_rht = GetLane(waypoint).GetRoad()->IsRHT();
if (is_rht){
if (waypoint.lane_id > 0) {
++waypoint.lane_id;
} else {
--waypoint.lane_id;
}
return IsLanePresent(_data, waypoint) ? waypoint : std::optional<Waypoint>{};
} else {
if (std::abs(waypoint.lane_id) == 1) {
waypoint.lane_id *= -1;
} else if (waypoint.lane_id > 0) {
--waypoint.lane_id;
} else {
++waypoint.lane_id;
}
return IsLanePresent(_data, waypoint) ? waypoint : std::optional<Waypoint>{};
}
}
std::optional<Waypoint> Map::GetLeft(Waypoint waypoint) const {
RELEASE_ASSERT(waypoint.lane_id != 0);
bool is_rht = GetLane(waypoint).GetRoad()->IsRHT();
if (is_rht){
if (std::abs(waypoint.lane_id) == 1) {
waypoint.lane_id *= -1;
} else if (waypoint.lane_id > 0) {
--waypoint.lane_id;
} else {
++waypoint.lane_id;
}
return IsLanePresent(_data, waypoint) ? waypoint : std::optional<Waypoint>{};
} else {
if (waypoint.lane_id > 0) {
++waypoint.lane_id;
} else {
--waypoint.lane_id;
}
return IsLanePresent(_data, waypoint) ? waypoint : std::optional<Waypoint>{};
}
}
std::vector<Waypoint> Map::GenerateWaypoints(const double distance) const {
RELEASE_ASSERT(distance > 0.0);
std::vector<Waypoint> result;
for (const auto &pair : _data.GetRoads()) {
const auto &road = pair.second;
for (double s = EPSILON; s < (road.GetLength() - EPSILON); s += distance) {
ForEachDrivableLaneAt(road, s, [&](auto &&waypoint) {
result.emplace_back(waypoint);
});
}
}
return result;
}
std::vector<Waypoint> Map::GenerateWaypointsOnRoadEntries(Lane::LaneType lane_type) const {
std::vector<Waypoint> result;
for (const auto &pair : _data.GetRoads()) {
const auto &road = pair.second;
// right lanes start at s 0
for (const auto &lane_section : road.GetLaneSectionsAt(0.0)) {
for (const auto &lane : lane_section.GetLanes()) {
if (lane.second.IsPositiveDirection() &&
static_cast<int32_t>(lane.second.GetType()) & static_cast<int32_t>(lane_type)) {
result.emplace_back(Waypoint{ road.GetId(), lane_section.GetId(), lane.second.GetId(), 0.0 });
}
}
}
// left lanes start at s max
const auto road_len = road.GetLength();
for (const auto &lane_section : road.GetLaneSectionsAt(road_len)) {
for (const auto &lane : lane_section.GetLanes()) {
// LHT reversed. add the right (negative) lanes
if (!lane.second.IsPositiveDirection() &&
static_cast<int32_t>(lane.second.GetType()) & static_cast<int32_t>(lane_type)) {
result.emplace_back(
Waypoint{ road.GetId(), lane_section.GetId(), lane.second.GetId(), road_len });
}
}
}
}
return result;
}
std::vector<Waypoint> Map::GenerateWaypointsInRoad(
RoadId road_id,
Lane::LaneType lane_type) const {
std::vector<Waypoint> result;
if(_data.GetRoads().count(road_id)) {
const auto &road = _data.GetRoads().at(road_id);
// right lanes start at s 0
for (const auto &lane_section : road.GetLaneSectionsAt(0.0)) {
for (const auto &lane : lane_section.GetLanes()) {
if (lane.second.IsPositiveDirection() &&
static_cast<int32_t>(lane.second.GetType()) & static_cast<int32_t>(lane_type)) {
result.emplace_back(Waypoint{ road.GetId(), lane_section.GetId(), lane.second.GetId(), 0.0 });
}
}
}
// left lanes start at s max
const auto road_len = road.GetLength();
for (const auto &lane_section : road.GetLaneSectionsAt(road_len)) {
for (const auto &lane : lane_section.GetLanes()) {
if (!lane.second.IsPositiveDirection() &&
static_cast<int32_t>(lane.second.GetType()) & static_cast<int32_t>(lane_type)) {
result.emplace_back(
Waypoint{ road.GetId(), lane_section.GetId(), lane.second.GetId(), road_len });
}
}
}
}
return result;
}
std::vector<std::pair<Waypoint, Waypoint>> Map::GenerateTopology() const {
std::vector<std::pair<Waypoint, Waypoint>> result;
for (const auto &pair : _data.GetRoads()) {
const auto &road = pair.second;
ForEachDrivableLane(road, [&](auto &&waypoint) {
auto successors = GetSuccessors(waypoint);
if (successors.size() == 0){
auto distance = static_cast<float>(GetDistanceAtEndOfLane(GetLane(waypoint)));
auto last_waypoint = GetWaypoint(waypoint.road_id, waypoint.lane_id, distance);
if (last_waypoint.has_value()){
result.push_back({waypoint, *last_waypoint});
}
}
else{
for (auto &&successor : GetSuccessors(waypoint)) {
result.push_back({waypoint, successor});
}
}
});
}
return result;
}
std::vector<std::pair<Waypoint, Waypoint>> Map::GetJunctionWaypoints(JuncId id, Lane::LaneType lane_type) const {
std::vector<std::pair<Waypoint, Waypoint>> result;
const Junction * junction = GetJunction(id);
for(auto &connections : junction->GetConnections()) {
const Road &road = _data.GetRoad(connections.second.connecting_road);
ForEachLane(road, lane_type, [&](auto &&waypoint) {
const auto& lane = GetLane(waypoint);
const double final_s = GetDistanceAtEndOfLane(lane);
Waypoint lane_end(waypoint);
lane_end.s = final_s;
result.push_back({waypoint, lane_end});
});
}
return result;
}
std::unordered_map<road::RoadId, std::unordered_set<road::RoadId>>
Map::ComputeJunctionConflicts(JuncId id) const {
const float epsilon = 0.0001f; // small delta in the road (set to 0.1
// millimeters to prevent numeric errors)
const Junction *junction = GetJunction(id);
std::unordered_map<road::RoadId, std::unordered_set<road::RoadId>>
conflicts;
// 2d typedefs
typedef boost::geometry::model::point
<float, 2, boost::geometry::cs::cartesian> Point2d;
typedef boost::geometry::model::segment<Point2d> Segment2d;
typedef boost::geometry::model::box<Rtree::BPoint> Box;
// box range
auto bbox_pos = junction->GetBoundingBox().location;
auto bbox_ext = junction->GetBoundingBox().extent;
auto min_corner = geom::Vector3D(
bbox_pos.x - bbox_ext.x,
bbox_pos.y - bbox_ext.y,
bbox_pos.z - bbox_ext.z - epsilon);
auto max_corner = geom::Vector3D(
bbox_pos.x + bbox_ext.x,
bbox_pos.y + bbox_ext.y,
bbox_pos.z + bbox_ext.z + epsilon);
Box box({min_corner.x, min_corner.y, min_corner.z},
{max_corner.x, max_corner.y, max_corner.z});
auto segments = _rtree.GetIntersections(box);
for (size_t i = 0; i < segments.size(); ++i){
auto &segment1 = segments[i];
auto waypoint1 = segment1.second.first;
JuncId junc_id1 = _data.GetRoad(waypoint1.road_id).GetJunctionId();
// only segments in the junction
if(junc_id1 != id){
continue;
}
Segment2d seg1{{segment1.first.first.get<0>(), segment1.first.first.get<1>()},
{segment1.first.second.get<0>(), segment1.first.second.get<1>()}};
for (size_t j = i + 1; j < segments.size(); ++j){
auto &segment2 = segments[j];
auto waypoint2 = segment2.second.first;
JuncId junc_id2 = _data.GetRoad(waypoint2.road_id).GetJunctionId();
// only segments in the junction
if(junc_id2 != id){
continue;
}
// discard same road
if(waypoint1.road_id == waypoint2.road_id){
continue;
}
Segment2d seg2{{segment2.first.first.get<0>(), segment2.first.first.get<1>()},
{segment2.first.second.get<0>(), segment2.first.second.get<1>()}};
double distance = boost::geometry::distance(seg1, seg2);
// better to set distance to lanewidth
if(distance > 2.0){
continue;
}
if(conflicts[waypoint1.road_id].count(waypoint2.road_id) == 0){
conflicts[waypoint1.road_id].insert(waypoint2.road_id);
}
if(conflicts[waypoint2.road_id].count(waypoint1.road_id) == 0){
conflicts[waypoint2.road_id].insert(waypoint1.road_id);
}
}
}
return conflicts;
}
const Lane &Map::GetLane(Waypoint waypoint) const {
return _data.GetRoad(waypoint.road_id).GetLaneById(waypoint.section_id, waypoint.lane_id);
}
// ===========================================================================
// -- Map: Private functions -------------------------------------------------
// ===========================================================================
// Adds a new element to the rtree element list using the position of the
// waypoints both ends of the segment
void Map::AddElementToRtree(
std::vector<Rtree::TreeElement> &rtree_elements,
geom::Transform ¤t_transform,
geom::Transform &next_transform,
Waypoint ¤t_waypoint,
Waypoint &next_waypoint) {
Rtree::BPoint init =
Rtree::BPoint(
current_transform.location.x,
current_transform.location.y,
current_transform.location.z);
Rtree::BPoint end =
Rtree::BPoint(
next_transform.location.x,
next_transform.location.y,
next_transform.location.z);
rtree_elements.emplace_back(std::make_pair(Rtree::BSegment(init, end),
std::make_pair(current_waypoint, next_waypoint)));
}
// Adds a new element to the rtree element list using the position of the
// waypoints, both ends of the segment
void Map::AddElementToRtreeAndUpdateTransforms(
std::vector<Rtree::TreeElement> &rtree_elements,
geom::Transform ¤t_transform,
Waypoint ¤t_waypoint,
Waypoint &next_waypoint) {
geom::Transform next_transform = ComputeTransform(next_waypoint);
AddElementToRtree(rtree_elements, current_transform, next_transform,
current_waypoint, next_waypoint);
current_waypoint = next_waypoint;
current_transform = next_transform;
}
// returns the remaining length of the geometry depending on the lane
// direction
double GetRemainingLength(const Lane &lane, double current_s) {
if (lane.IsPositiveDirection()) {
return (lane.GetDistance() + lane.GetLength() - current_s);
} else {
return (current_s - lane.GetDistance());
}
}
void Map::CreateRtree() {
const double epsilon = 0.000001; // small delta in the road (set to 1
// micrometer to prevent numeric errors)
const double min_delta_s = 1; // segments of minimum 1m through the road
// 1.8 degrees, maximum angle in a curve to place a segment
constexpr double angle_threshold = geom::Math::Pi<double>() / 100.0;
// maximum distance of a segment
constexpr double max_segment_length = 100.0;
// Generate waypoints at start of every lane
std::vector<Waypoint> topology;
for (const auto &pair : _data.GetRoads()) {
const auto &road = pair.second;
ForEachLane(road, Lane::LaneType::Any, [&](auto &&waypoint) {
if(waypoint.lane_id != 0) {
topology.push_back(waypoint);
}
});
}
// Container of segments and waypoints
std::vector<Rtree::TreeElement> rtree_elements;
// Loop through all lanes
for (auto &waypoint : topology) {
auto &lane_start_waypoint = waypoint;
auto current_waypoint = lane_start_waypoint;
const Lane &lane = GetLane(current_waypoint);
geom::Transform current_transform = ComputeTransform(current_waypoint);
// Save computation time in straight lines
if (lane.IsStraight()) {
double delta_s = min_delta_s;
double remaining_length =
GetRemainingLength(lane, current_waypoint.s);
remaining_length -= epsilon;
delta_s = remaining_length;
if (delta_s < epsilon) {
continue;
}
auto next = GetNext(current_waypoint, delta_s);
RELEASE_ASSERT(next.size() == 1);
RELEASE_ASSERT(next.front().road_id == current_waypoint.road_id);
auto next_waypoint = next.front();
AddElementToRtreeAndUpdateTransforms(
rtree_elements,
current_transform,
current_waypoint,
next_waypoint);
// end of lane
} else {
auto next_waypoint = current_waypoint;
// Loop until the end of the lane
// Advance in small s-increments
while (true) {
double delta_s = min_delta_s;
double remaining_length =
GetRemainingLength(lane, next_waypoint.s);
remaining_length -= epsilon;
delta_s = std::min(delta_s, remaining_length);
if (delta_s < epsilon) {
AddElementToRtreeAndUpdateTransforms(
rtree_elements,
current_transform,
current_waypoint,
next_waypoint);
break;
}
auto next = GetNext(next_waypoint, delta_s);
if (next.size() != 1 ||
current_waypoint.section_id != next.front().section_id) {
AddElementToRtreeAndUpdateTransforms(
rtree_elements,
current_transform,
current_waypoint,
next_waypoint);
break;
}
next_waypoint = next.front();
geom::Transform next_transform = ComputeTransform(next_waypoint);
double angle = geom::Math::GetVectorAngle(
current_transform.GetForwardVector(), next_transform.GetForwardVector());
if (std::abs(angle) > angle_threshold ||
std::abs(current_waypoint.s - next_waypoint.s) > max_segment_length) {