-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
NBEdge.cpp
4837 lines (4435 loc) · 191 KB
/
NBEdge.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
/****************************************************************************/
// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
// Copyright (C) 2001-2024 German Aerospace Center (DLR) and others.
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0/
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License 2.0 are satisfied: GNU General Public License, version 2
// or later which is available at
// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
/****************************************************************************/
/// @file NBEdge.cpp
/// @author Daniel Krajzewicz
/// @author Jakob Erdmann
/// @author Sascha Krieg
/// @author Michael Behrisch
/// @author Laura Bieker
/// @author Leonhard Luecken
/// @date Tue, 20 Nov 2001
///
// Methods for the representation of a single edge
/****************************************************************************/
#include <config.h>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <utils/common/MsgHandler.h>
#include <utils/common/StringTokenizer.h>
#include <utils/common/StringUtils.h>
#include <utils/common/ToString.h>
#include <utils/common/UtilExceptions.h>
#include <utils/common/StdDefs.h>
#include <utils/geom/GeomHelper.h>
#include <utils/options/OptionsCont.h>
#include "NBEdgeCont.h"
#include "NBNode.h"
#include "NBNodeCont.h"
#include "NBContHelper.h"
#include "NBHelpers.h"
#include "NBTrafficLightDefinition.h"
#include "NBOwnTLDef.h"
#include "NBTypeCont.h"
#include "NBEdge.h"
//#define ADDITIONAL_WARNINGS
//#define DEBUG_CONNECTION_GUESSING
//#define DEBUG_ANGLES
//#define DEBUG_NODE_BORDER
//#define DEBUG_REPLACECONNECTION
//#define DEBUG_JUNCTIONPRIO
//#define DEBUG_TURNSIGNS
//#define DEBUG_CUT_LANES
#define DEBUGID ""
#define DEBUGCOND (getID() == DEBUGID)
//#define DEBUGCOND (StringUtils::startsWith(getID(), DEBUGID))
//#define DEBUGCOND (getID() == "22762377#1" || getID() == "146511467")
#define DEBUGCOND2(obj) ((obj != 0 && (obj)->getID() == DEBUGID))
//#define DEBUGCOND (true)
// ===========================================================================
// static members
// ===========================================================================
const double NBEdge::UNSPECIFIED_WIDTH = -1;
const double NBEdge::UNSPECIFIED_OFFSET = 0;
const double NBEdge::UNSPECIFIED_SPEED = -1;
const double NBEdge::UNSPECIFIED_FRICTION = 1.;
const double NBEdge::UNSPECIFIED_CONTPOS = -1;
const double NBEdge::UNSPECIFIED_VISIBILITY_DISTANCE = -1;
const double NBEdge::UNSPECIFIED_SIGNAL_OFFSET = -1;
const double NBEdge::UNSPECIFIED_LOADED_LENGTH = -1;
const double NBEdge::ANGLE_LOOKAHEAD = 10.0;
const int NBEdge::UNSPECIFIED_INTERNAL_LANE_INDEX = -1;
const bool NBEdge::UNSPECIFIED_CONNECTION_UNCONTROLLED = false;
double NBEdge::myDefaultConnectionLength = NBEdge::UNSPECIFIED_LOADED_LENGTH;
NBEdge NBEdge::DummyEdge;
ConstRouterEdgePairVector NBEdge::Connection::myViaSuccessors = ConstRouterEdgePairVector({ std::pair<NBRouterEdge*, NBRouterEdge*>(nullptr, nullptr) });
// ===========================================================================
// method definitions
// ===========================================================================
std::string
NBEdge::Connection::getInternalLaneID() const {
return id + "_" + toString(internalLaneIndex);
}
std::string
NBEdge::Connection::getDescription(const NBEdge* parent) const {
return (Named::getIDSecure(parent) + "_" + toString(fromLane) + "->" + Named::getIDSecure(toEdge) + "_" + toString(toLane)
+ (permissions == SVC_UNSPECIFIED ? "" : " (" + getVehicleClassNames(permissions) + ")"));
}
NBEdge::Connection::Connection(int fromLane_, NBEdge* toEdge_, int toLane_, const bool mayDefinitelyPass_) :
fromLane(fromLane_),
toEdge(toEdge_),
toLane(toLane_),
mayDefinitelyPass(mayDefinitelyPass_),
customLength(myDefaultConnectionLength),
id(toEdge_ == nullptr ? "" : toEdge->getFromNode()->getID()) {
}
NBEdge::Lane::Lane(NBEdge* e, const std::string& origID_) :
speed(e->getSpeed()),
friction(e->getFriction()),
permissions(SVCAll),
preferred(0),
changeLeft(SVCAll),
changeRight(SVCAll),
endOffset(e->getEndOffset()),
laneStopOffset(e->getEdgeStopOffset()),
width(e->getLaneWidth()),
accelRamp(false),
connectionsDone(false) {
if (origID_ != "") {
setParameter(SUMO_PARAM_ORIGID, origID_);
}
}
/* -------------------------------------------------------------------------
* NBEdge::ToEdgeConnectionsAdder-methods
* ----------------------------------------------------------------------- */
void
NBEdge::ToEdgeConnectionsAdder::execute(const int lane, const int virtEdge) {
// check
assert((int)myTransitions.size() > virtEdge);
// get the approached edge
NBEdge* succEdge = myTransitions[virtEdge];
std::vector<int> lanes;
// check whether the currently regarded, approached edge has already
// a connection starting at the edge which is currently being build
std::map<NBEdge*, std::vector<int> >::iterator i = myConnections.find(succEdge);
if (i != myConnections.end()) {
// if there were already lanes assigned, get them
lanes = (*i).second;
}
// check whether the current lane was already used to connect the currently
// regarded approached edge
std::vector<int>::iterator j = std::find(lanes.begin(), lanes.end(), lane);
if (j == lanes.end()) {
// if not, add it to the list
lanes.push_back(lane);
}
// set information about connecting lanes
myConnections[succEdge] = lanes;
}
/* -------------------------------------------------------------------------
* NBEdge::MainDirections-methods
* ----------------------------------------------------------------------- */
NBEdge::MainDirections::MainDirections(const EdgeVector& outgoing, NBEdge* parent, NBNode* to, const std::vector<int>& availableLanes) : myStraightest(-1) {
NBContHelper::edge_similar_direction_sorter sorter(parent);
const NBEdge* straight = nullptr;
for (const NBEdge* const out : outgoing) {
const SVCPermissions outPerms = out->getPermissions();
for (const int l : availableLanes) {
if ((parent->myLanes[l].permissions & outPerms) != 0) {
if (straight == nullptr || sorter(out, straight)) {
straight = out;
}
break;
}
}
}
if (straight == nullptr) {
return;
}
myStraightest = (int)std::distance(outgoing.begin(), std::find(outgoing.begin(), outgoing.end(), straight));
// check whether the right turn has a higher priority
assert(outgoing.size() > 0);
const LinkDirection straightestDir = to->getDirection(parent, straight);
#ifdef DEBUG_CONNECTION_GUESSING
if (DEBUGCOND2(parent)) {
std::cout << " MainDirections edge=" << parent->getID() << " straightest=" << straight->getID() << " dir=" << toString(straightestDir) << "\n";
}
#endif
if (NBNode::isTrafficLight(to->getType()) &&
(straightestDir == LinkDirection::STRAIGHT || straightestDir == LinkDirection::PARTLEFT || straightestDir == LinkDirection::PARTRIGHT)) {
myDirs.push_back(MainDirections::Direction::FORWARD);
return;
}
if (outgoing[0]->getJunctionPriority(to) == 1) {
myDirs.push_back(MainDirections::Direction::RIGHTMOST);
}
// check whether the left turn has a higher priority
if (outgoing.back()->getJunctionPriority(to) == 1) {
// ok, the left turn belongs to the higher priorised edges on the junction
// let's check, whether it has also a higher priority (lane number/speed)
// than the current
if (outgoing.back()->getPriority() > straight->getPriority() ||
outgoing.back()->getNumLanes() > straight->getNumLanes()) {
myDirs.push_back(MainDirections::Direction::LEFTMOST);
}
}
// check whether the forward direction has a higher priority
// check whether it has a higher priority and is going straight
if (straight->getJunctionPriority(to) == 1 && to->getDirection(parent, straight) == LinkDirection::STRAIGHT) {
myDirs.push_back(MainDirections::Direction::FORWARD);
}
}
NBEdge::MainDirections::~MainDirections() {}
bool
NBEdge::MainDirections::empty() const {
return myDirs.empty();
}
bool
NBEdge::MainDirections::includes(Direction d) const {
return std::find(myDirs.begin(), myDirs.end(), d) != myDirs.end();
}
/* -------------------------------------------------------------------------
* NBEdge::connections_relative_edgelane_sorter-methods
* ----------------------------------------------------------------------- */
int
NBEdge::connections_relative_edgelane_sorter::operator()(const Connection& c1, const Connection& c2) const {
if (c1.toEdge != c2.toEdge) {
return NBContHelper::relative_outgoing_edge_sorter(myEdge)(c1.toEdge, c2.toEdge);
}
return c1.toLane < c2.toLane;
}
/* -------------------------------------------------------------------------
* NBEdge-methods
* ----------------------------------------------------------------------- */
NBEdge::NBEdge(const std::string& id, NBNode* from, NBNode* to,
std::string type, double speed, double friction, int nolanes,
int priority, double laneWidth, double endOffset,
LaneSpreadFunction spread, const std::string& streetName) :
Named(StringUtils::convertUmlaute(id)),
myStep(EdgeBuildingStep::INIT),
myType(StringUtils::convertUmlaute(type)),
myFrom(from), myTo(to),
myStartAngle(0), myEndAngle(0), myTotalAngle(0),
myPriority(priority), mySpeed(speed), myFriction(friction),
myDistance(0),
myTurnDestination(nullptr),
myPossibleTurnDestination(nullptr),
myFromJunctionPriority(-1), myToJunctionPriority(-1),
myLaneSpreadFunction(spread), myEndOffset(endOffset),
myLaneWidth(laneWidth),
myLoadedLength(UNSPECIFIED_LOADED_LENGTH),
myAmInTLS(false), myAmMacroscopicConnector(false),
myStreetName(streetName),
mySignalPosition(Position::INVALID),
mySignalNode(nullptr),
myIsOffRamp(false),
myIsBidi(false),
myIndex(-1) {
init(nolanes, false, "");
}
NBEdge::NBEdge(const std::string& id, NBNode* from, NBNode* to,
std::string type, double speed, double friction, int nolanes,
int priority, double laneWidth, double endOffset,
PositionVector geom,
LaneSpreadFunction spread,
const std::string& streetName,
const std::string& origID,
bool tryIgnoreNodePositions) :
Named(StringUtils::convertUmlaute(id)),
myStep(EdgeBuildingStep::INIT),
myType(StringUtils::convertUmlaute(type)),
myFrom(from), myTo(to),
myStartAngle(0), myEndAngle(0), myTotalAngle(0),
myPriority(priority), mySpeed(speed), myFriction(friction),
myDistance(0),
myTurnDestination(nullptr),
myPossibleTurnDestination(nullptr),
myFromJunctionPriority(-1), myToJunctionPriority(-1),
myGeom(geom), myLaneSpreadFunction(spread), myEndOffset(endOffset),
myLaneWidth(laneWidth),
myLoadedLength(UNSPECIFIED_LOADED_LENGTH),
myAmInTLS(false), myAmMacroscopicConnector(false),
myStreetName(streetName),
mySignalPosition(Position::INVALID),
mySignalNode(nullptr),
myIsOffRamp(false),
myIsBidi(false),
myIndex(-1) {
init(nolanes, tryIgnoreNodePositions, origID);
}
NBEdge::NBEdge(const std::string& id, NBNode* from, NBNode* to, const NBEdge* tpl, const PositionVector& geom, int numLanes) :
Named(StringUtils::convertUmlaute(id)),
myStep(EdgeBuildingStep::INIT),
myType(tpl->getTypeID()),
myFrom(from), myTo(to),
myStartAngle(0), myEndAngle(0), myTotalAngle(0),
myPriority(tpl->getPriority()), mySpeed(tpl->getSpeed()),
myFriction(tpl->getFriction()),
myDistance(0),
myTurnDestination(nullptr),
myPossibleTurnDestination(nullptr),
myFromJunctionPriority(-1), myToJunctionPriority(-1),
myGeom(geom),
myLaneSpreadFunction(tpl->getLaneSpreadFunction()),
myEndOffset(tpl->getEndOffset()),
myEdgeStopOffset(tpl->getEdgeStopOffset()),
myLaneWidth(tpl->getLaneWidth()),
myLoadedLength(UNSPECIFIED_LOADED_LENGTH),
myAmInTLS(false),
myAmMacroscopicConnector(false),
myStreetName(tpl->getStreetName()),
mySignalPosition(to == tpl->myTo ? tpl->mySignalPosition : Position::INVALID),
mySignalNode(to == tpl->myTo ? tpl->mySignalNode : nullptr),
myIsOffRamp(false),
myIsBidi(false),
myIndex(-1) {
init(numLanes > 0 ? numLanes : tpl->getNumLanes(), myGeom.size() > 0, "");
for (int i = 0; i < getNumLanes(); i++) {
const int tplIndex = MIN2(i, tpl->getNumLanes() - 1);
setSpeed(i, tpl->getLaneSpeed(tplIndex));
setFriction(i, tpl->getLaneFriction(tplIndex));
setPermissions(tpl->getPermissions(tplIndex), i);
setLaneWidth(i, tpl->myLanes[tplIndex].width);
setLaneType(i, tpl->myLanes[tplIndex].type);
myLanes[i].updateParameters(tpl->myLanes[tplIndex].getParametersMap());
if (to == tpl->myTo) {
setEndOffset(i, tpl->myLanes[tplIndex].endOffset);
setEdgeStopOffset(i, tpl->myLanes[tplIndex].laneStopOffset);
}
}
if (tpl->myLoadedLength > 0 && to == tpl->getFromNode() && from == tpl->getToNode() && geom == tpl->getGeometry().reverse()) {
myLoadedLength = tpl->myLoadedLength;
}
updateParameters(tpl->getParametersMap());
}
NBEdge::NBEdge() :
Named("DUMMY"),
myStep(EdgeBuildingStep::INIT),
myFrom(nullptr), myTo(nullptr),
myStartAngle(0), myEndAngle(0), myTotalAngle(0),
myPriority(0), mySpeed(0), myFriction(UNSPECIFIED_FRICTION),
myDistance(0),
myTurnDestination(nullptr),
myPossibleTurnDestination(nullptr),
myFromJunctionPriority(-1), myToJunctionPriority(-1),
myLaneSpreadFunction(LaneSpreadFunction::RIGHT),
myEndOffset(0),
myEdgeStopOffset(StopOffset()),
myLaneWidth(0),
myLoadedLength(UNSPECIFIED_LOADED_LENGTH),
myAmInTLS(false),
myAmMacroscopicConnector(false),
mySignalPosition(Position::INVALID),
mySignalNode(nullptr) {
}
void
NBEdge::reinit(NBNode* from, NBNode* to, const std::string& type,
double speed, double friction, int nolanes, int priority,
PositionVector geom, double laneWidth, double endOffset,
const std::string& streetName,
LaneSpreadFunction spread,
bool tryIgnoreNodePositions) {
if (myFrom != from) {
myFrom->removeEdge(this, false);
}
if (myTo != to) {
myTo->removeEdge(this, false);
}
myType = StringUtils::convertUmlaute(type);
myFrom = from;
myTo = to;
myPriority = priority;
//?myTurnDestination(0),
//?myFromJunctionPriority(-1), myToJunctionPriority(-1),
myGeom = geom;
myLaneSpreadFunction = spread;
myLoadedLength = UNSPECIFIED_LOADED_LENGTH;
myStreetName = streetName;
//?, myAmTurningWithAngle(0), myAmTurningOf(0),
//?myAmInTLS(false), myAmMacroscopicConnector(false)
// preserve lane-specific settings (geometry must be recomputed)
// if new lanes are added they copy the values from the leftmost lane (if specified)
const std::vector<Lane> oldLanes = myLanes;
init(nolanes, tryIgnoreNodePositions, oldLanes.empty() ? "" : oldLanes[0].getParameter(SUMO_PARAM_ORIGID));
for (int i = 0; i < (int)nolanes; ++i) {
PositionVector newShape = myLanes[i].shape;
myLanes[i] = oldLanes[MIN2(i, (int)oldLanes.size() - 1)];
myLanes[i].shape = newShape;
}
// however, if the new edge defaults are explicityly given, they override the old settings
if (endOffset != UNSPECIFIED_OFFSET) {
setEndOffset(-1, endOffset);
}
if (laneWidth != UNSPECIFIED_WIDTH) {
setLaneWidth(-1, laneWidth);
}
if (speed != UNSPECIFIED_SPEED) {
setSpeed(-1, speed);
}
if (friction != UNSPECIFIED_FRICTION) {
setFriction(-1, friction);
}
}
void
NBEdge::reinitNodes(NBNode* from, NBNode* to) {
// connections may still be valid
if (from == nullptr || to == nullptr) {
throw ProcessError(TLF("At least one of edge's '%' nodes is not known.", myID));
}
if (myFrom != from) {
myFrom->removeEdge(this, false);
}
if (myTo != to) {
myTo->removeEdge(this, false);
}
// remove first from both nodes and then add to the new nodes
// (otherwise reversing does not work)
if (myFrom != from) {
myFrom = from;
myFrom->addOutgoingEdge(this);
}
if (myTo != to) {
myTo = to;
myTo->addIncomingEdge(this);
}
computeAngle();
}
void
NBEdge::init(int noLanes, bool tryIgnoreNodePositions, const std::string& origID) {
if (noLanes == 0) {
throw ProcessError(TLF("Edge '%' needs at least one lane.", myID));
}
if (myFrom == nullptr || myTo == nullptr) {
throw ProcessError(TLF("At least one of edge's '%' nodes is not known.", myID));
}
if (!SUMOXMLDefinitions::isValidNetID(myID)) {
throw ProcessError(TLF("Invalid edge id '%'.", myID));
}
// revisit geometry
// should have at least two points at the end...
// and in dome cases, the node positions must be added
// attempt symmetrical removal for forward and backward direction
// (very important for bidiRail)
if (myFrom->getID() < myTo->getID()) {
PositionVector reverse = myGeom.reverse();
reverse.removeDoublePoints(POSITION_EPS, true);
myGeom = reverse.reverse();
} else {
myGeom.removeDoublePoints(POSITION_EPS, true);
}
if (!tryIgnoreNodePositions || myGeom.size() < 2) {
if (myGeom.size() == 0) {
myGeom.push_back(myFrom->getPosition());
myGeom.push_back(myTo->getPosition());
} else {
myGeom.push_back_noDoublePos(myTo->getPosition());
myGeom.push_front_noDoublePos(myFrom->getPosition());
}
}
if (myGeom.size() < 2) {
myGeom.clear();
myGeom.push_back(myFrom->getPosition());
myGeom.push_back(myTo->getPosition());
}
if (myGeom.size() == 2 && myGeom[0] == myGeom[1]) {
WRITE_WARNINGF(TL("Edge's '%' from- and to-node are at the same position."), myID);
int patchIndex = myFrom->getID() < myTo->getID() ? 1 : 0;
myGeom[patchIndex].add(Position(POSITION_EPS, POSITION_EPS));
}
//
myFrom->addOutgoingEdge(this);
myTo->addIncomingEdge(this);
// prepare container
assert(myGeom.size() >= 2);
myLength = myGeom.length();
if ((int)myLanes.size() > noLanes) {
// remove connections starting at the removed lanes
for (int lane = noLanes; lane < (int)myLanes.size(); ++lane) {
removeFromConnections(nullptr, lane, -1);
}
// remove connections targeting the removed lanes
const EdgeVector& incoming = myFrom->getIncomingEdges();
for (EdgeVector::const_iterator i = incoming.begin(); i != incoming.end(); i++) {
for (int lane = noLanes; lane < (int)myLanes.size(); ++lane) {
(*i)->removeFromConnections(this, -1, lane);
}
}
}
myLanes.clear();
for (int i = 0; i < noLanes; i++) {
myLanes.push_back(Lane(this, origID));
}
computeLaneShapes();
computeAngle();
#ifdef DEBUG_CONNECTION_GUESSING
if (DEBUGCOND) {
std::cout << "init edge=" << getID() << "\n";
for (Connection& c : myConnections) {
std::cout << " conn " << c.getDescription(this) << "\n";
}
for (Connection& c : myConnectionsToDelete) {
std::cout << " connToDelete " << c.getDescription(this) << "\n";
}
}
#endif
}
NBEdge::~NBEdge() {}
// ----------- Applying offset
void
NBEdge::reshiftPosition(double xoff, double yoff) {
myGeom.add(xoff, yoff, 0);
for (Lane& lane : myLanes) {
lane.customShape.add(xoff, yoff, 0);
}
computeLaneShapes(); // old shapes are dubious if computed with large coordinates
for (std::vector<Connection>::iterator i = myConnections.begin(); i != myConnections.end(); ++i) {
(*i).customShape.add(xoff, yoff, 0);
}
if (mySignalPosition != Position::INVALID) {
mySignalPosition.add(xoff, yoff);
}
myFromBorder.add(xoff, yoff, 0);
myToBorder.add(xoff, yoff, 0);
computeEdgeShape();
computeAngle(); // update angles because they are numerically sensitive (especially where based on centroids)
}
void
NBEdge::mirrorX() {
myGeom.mirrorX();
for (int i = 0; i < (int)myLanes.size(); i++) {
myLanes[i].shape.mirrorX();
myLanes[i].customShape.mirrorX();
}
for (Connection& c : myConnections) {
c.shape.mirrorX();
c.viaShape.mirrorX();
c.customShape.mirrorX();
}
if (mySignalPosition != Position::INVALID) {
mySignalPosition.sety(-mySignalPosition.y());
}
computeAngle(); // update angles because they are numerically sensitive (especially where based on centroids)
}
// ----------- Edge geometry access and computation
const PositionVector
NBEdge::getInnerGeometry() const {
return myGeom.getSubpartByIndex(1, (int)myGeom.size() - 2);
}
bool
NBEdge::hasDefaultGeometry() const {
return myGeom.size() == 2 && hasDefaultGeometryEndpoints();
}
bool
NBEdge::hasDefaultGeometryEndpoints() const {
return myGeom.front().almostSame(myFrom->getPosition(), 0.01) &&
myGeom.back().almostSame(myTo->getPosition(), 0.01);
}
bool
NBEdge::hasDefaultGeometryEndpointAtNode(const NBNode* node) const {
// do not extend past the node position
if (node == myFrom) {
return myGeom.front() == node->getPosition();
} else {
assert(node == myTo);
return myGeom.back() == node->getPosition();
}
}
Position
NBEdge::getEndpointAtNode(const NBNode* node) const {
return node == myFrom ? myGeom.front() : myGeom.back();
}
void
NBEdge::setGeometry(const PositionVector& s, bool inner) {
Position begin = myGeom.front(); // may differ from node position
Position end = myGeom.back(); // may differ from node position
myGeom = s;
if (inner) {
myGeom.insert(myGeom.begin(), begin);
myGeom.push_back(end);
}
// ensure non-zero length (see ::init)
if (myGeom.size() == 2 && myGeom[0] == myGeom[1]) {
WRITE_WARNINGF(TL("Edge's '%' from- and to-node are at the same position."), myID);
int patchIndex = myFrom->getID() < myTo->getID() ? 1 : 0;
myGeom[patchIndex].add(Position(POSITION_EPS, POSITION_EPS));
}
computeLaneShapes();
computeAngle();
myLength = myGeom.length();
}
void
NBEdge::extendGeometryAtNode(const NBNode* node, double maxExtent) {
//std::cout << "extendGeometryAtNode edge=" << getID() << " node=" << node->getID() << " nodePos=" << node->getPosition() << " extent=" << maxExtent << " geom=" << myGeom;
if (node == myFrom) {
myGeom.extrapolate(maxExtent, true);
double offset = myGeom.nearest_offset_to_point2D(node->getPosition());
//std::cout << " geom2=" << myGeom << " offset=" << offset;
if (offset != GeomHelper::INVALID_OFFSET) {
myGeom = myGeom.getSubpart2D(MIN2(offset, myGeom.length2D() - 2 * POSITION_EPS), myGeom.length2D());
}
} else {
assert(node == myTo);
myGeom.extrapolate(maxExtent, false, true);
double offset = myGeom.nearest_offset_to_point2D(node->getPosition());
//std::cout << " geom2=" << myGeom << " offset=" << offset;
if (offset != GeomHelper::INVALID_OFFSET) {
myGeom = myGeom.getSubpart2D(0, MAX2(offset, 2 * POSITION_EPS));
}
}
//std::cout << " geom3=" << myGeom << "\n";
}
void
NBEdge::shortenGeometryAtNode(const NBNode* node, double reduction) {
//std::cout << "shortenGeometryAtNode edge=" << getID() << " node=" << node->getID() << " nodePos=" << node->getPosition() << " reduction=" << reduction << " geom=" << myGeom;
reduction = MIN2(reduction, myGeom.length2D() - 2 * POSITION_EPS);
if (node == myFrom) {
myGeom = myGeom.getSubpart2D(reduction, myGeom.length2D());
} else {
myGeom = myGeom.getSubpart2D(0, myGeom.length2D() - reduction);
}
computeLaneShapes();
//std::cout << " geom2=" << myGeom << "\n";
}
void
NBEdge::setNodeBorder(const NBNode* node, const Position& p, const Position& p2, bool rectangularCut) {
PositionVector border;
if (rectangularCut) {
const double extend = 100;
border = myGeom.getOrthogonal(p, extend, node == myTo);
} else {
border.push_back(p);
border.push_back(p2);
}
if (border.size() == 2) {
border.extrapolate2D(getTotalWidth());
if (node == myFrom) {
myFromBorder = border;
} else {
assert(node == myTo);
myToBorder = border;
}
}
#ifdef DEBUG_NODE_BORDER
gDebugFlag1 = DEBUGCOND;
if (DEBUGCOND) std::cout << "setNodeBorder edge=" << getID() << " node=" << node->getID()
<< " rect=" << rectangularCut
<< " p=" << p << " p2=" << p2
<< " border=" << border
<< " myGeom=" << myGeom
<< "\n";
#endif
}
const PositionVector&
NBEdge::getNodeBorder(const NBNode* node) const {
if (node == myFrom) {
return myFromBorder;
} else {
assert(node == myTo);
return myToBorder;
}
}
void
NBEdge::resetNodeBorder(const NBNode* node) {
if (node == myFrom) {
myFromBorder.clear();
} else {
assert(node == myTo);
myToBorder.clear();
}
}
bool
NBEdge::isBidiRail(bool ignoreSpread) const {
return (isRailway(getPermissions())
&& (ignoreSpread || myLaneSpreadFunction == LaneSpreadFunction::CENTER)
&& myPossibleTurnDestination != nullptr
&& myPossibleTurnDestination->myPossibleTurnDestination == this
&& (ignoreSpread || myPossibleTurnDestination->getLaneSpreadFunction() == LaneSpreadFunction::CENTER)
&& isRailway(myPossibleTurnDestination->getPermissions())
&& myPossibleTurnDestination->getGeometry().reverse() == getGeometry());
}
bool
NBEdge::isBidiEdge(bool checkPotential) const {
return myPossibleTurnDestination != nullptr
&& myPossibleTurnDestination->myPossibleTurnDestination == this
&& (myIsBidi || myPossibleTurnDestination->myIsBidi || checkPotential)
&& myPossibleTurnDestination->getToNode() == getFromNode()
&& myPossibleTurnDestination->getLaneSpreadFunction() == myLaneSpreadFunction
// geometry check a) full overlap geometry
&& ((myLaneSpreadFunction == LaneSpreadFunction::CENTER
&& (myPossibleTurnDestination->getGeometry().reverse() == getGeometry()
|| (checkPotential && getGeometry().size() == 2 && myPossibleTurnDestination->getGeometry().size() == 2)))
// b) TWLT (Two-Way-Left-Turn-lane)
|| (myLanes.back().shape.reverse().almostSame(myPossibleTurnDestination->myLanes.back().shape, POSITION_EPS))
);
}
bool
NBEdge::isRailDeadEnd() const {
if (!isRailway(getPermissions())) {
return false;
}
for (NBEdge* out : myTo->getOutgoingEdges()) {
if (isRailway(out->getPermissions()) &&
out != getTurnDestination(true)) {
return true;
}
}
return true;
}
PositionVector
NBEdge::cutAtIntersection(const PositionVector& old) const {
PositionVector shape = old;
shape = startShapeAt(shape, myFrom, myFromBorder);
#ifdef DEBUG_CUT_LANES
if (DEBUGCOND) std::cout << getID() << " cutFrom=" << shape << "\n";
#endif
if (shape.size() < 2) {
// only keep the last snippet
const double oldLength = old.length();
shape = old.getSubpart(oldLength - 2 * POSITION_EPS, oldLength);
#ifdef DEBUG_CUT_LANES
if (DEBUGCOND) std::cout << getID() << " cutFromFallback=" << shape << "\n";
#endif
}
shape = startShapeAt(shape.reverse(), myTo, myToBorder).reverse();
#ifdef DEBUG_CUT_LANES
if (DEBUGCOND) std::cout << getID() << " cutTo=" << shape << "\n";
#endif
// sanity checks
if (shape.length() < POSITION_EPS) {
if (old.length() < 2 * POSITION_EPS) {
shape = old;
} else {
const double midpoint = old.length() / 2;
// EPS*2 because otherwhise shape has only a single point
shape = old.getSubpart(midpoint - POSITION_EPS, midpoint + POSITION_EPS);
assert(shape.size() >= 2);
assert(shape.length() > 0);
#ifdef DEBUG_CUT_LANES
if (DEBUGCOND) std::cout << getID() << " fallBackShort=" << shape << "\n";
#endif
}
} else {
// @note If the node shapes are overlapping we may get a shape which goes in the wrong direction
// in this case the result shape should shortened
if (DEG2RAD(135) < fabs(GeomHelper::angleDiff(shape.beginEndAngle(), old.beginEndAngle()))) {
// eliminate intermediate points
PositionVector tmp;
tmp.push_back(shape[0]);
tmp.push_back(shape[-1]);
shape = tmp;
if (tmp.length() < POSITION_EPS) {
// fall back to original shape
if (old.length() < 2 * POSITION_EPS) {
shape = old;
} else {
const double midpoint = old.length() / 2;
// EPS*2 because otherwhise shape has only a single point
shape = old.getSubpart(midpoint - POSITION_EPS, midpoint + POSITION_EPS);
assert(shape.size() >= 2);
assert(shape.length() > 0);
}
#ifdef DEBUG_CUT_LANES
if (DEBUGCOND) std::cout << getID() << " fallBackReversed=" << shape << "\n";
#endif
} else {
const double midpoint = shape.length() / 2;
// cut to size and reverse
shape = shape.getSubpart(midpoint - POSITION_EPS, midpoint + POSITION_EPS);
if (shape.length() < POSITION_EPS) {
assert(false);
// the shape has a sharp turn near the midpoint
}
shape = shape.reverse();
#ifdef DEBUG_CUT_LANES
if (DEBUGCOND) std::cout << getID() << " fallBackReversed2=" << shape << " mid=" << midpoint << "\n";
#endif
}
// make short edge flat (length <= 2 * POSITION_EPS)
const double z = (shape[0].z() + shape[1].z()) / 2;
shape[0].setz(z);
shape[1].setz(z);
}
}
return shape;
}
void
NBEdge::computeEdgeShape(double smoothElevationThreshold) {
if (smoothElevationThreshold > 0 && myGeom.hasElevation()) {
PositionVector cut = cutAtIntersection(myGeom);
// cutting and patching z-coordinate may cause steep grades which should be smoothed
if (!myFrom->geometryLike()) {
cut[0].setz(myFrom->getPosition().z());
const double d = cut[0].distanceTo2D(cut[1]);
const double dZ = fabs(cut[0].z() - cut[1].z());
if (dZ / smoothElevationThreshold > d) {
cut = cut.smoothedZFront(MIN2(cut.length2D() / 2, dZ / smoothElevationThreshold));
}
}
if (!myTo->geometryLike()) {
cut[-1].setz(myTo->getPosition().z());
const double d = cut[-1].distanceTo2D(cut[-2]);
const double dZ = fabs(cut[-1].z() - cut[-2].z());
if (dZ / smoothElevationThreshold > d) {
cut = cut.reverse().smoothedZFront(MIN2(cut.length2D() / 2, dZ / smoothElevationThreshold)).reverse();
}
}
cut[0] = myGeom[0];
cut[-1] = myGeom[-1];
if (cut != myGeom) {
myGeom = cut;
computeLaneShapes();
}
}
for (int i = 0; i < (int)myLanes.size(); i++) {
myLanes[i].shape = cutAtIntersection(myLanes[i].shape);
}
// recompute edge's length as the average of lane lengths
double avgLength = 0;
for (int i = 0; i < (int)myLanes.size(); i++) {
avgLength += myLanes[i].shape.length();
}
myLength = avgLength / (double) myLanes.size();
computeAngle(); // update angles using the finalized node and lane shapes
}
PositionVector
NBEdge::startShapeAt(const PositionVector& laneShape, const NBNode* startNode, PositionVector nodeShape) {
if (nodeShape.size() == 0) {
nodeShape = startNode->getShape();
nodeShape.closePolygon();
}
PositionVector lb = laneShape;
lb.extrapolate2D(100.0);
if (nodeShape.intersects(laneShape)) {
// shape intersects directly
std::vector<double> pbv = laneShape.intersectsAtLengths2D(nodeShape);
assert(pbv.size() > 0);
// ensure that the subpart has at least two points
double pb = MIN2(laneShape.length2D() - POSITION_EPS - NUMERICAL_EPS, VectorHelper<double>::maxValue(pbv));
if (pb < 0) {
return laneShape;
}
PositionVector ns = laneShape.getSubpart2D(pb, laneShape.length2D());
//PositionVector ns = pb < (laneShape.length() - POSITION_EPS) ? laneShape.getSubpart2D(pb, laneShape.length()) : laneShape;
const double delta = ns[0].z() - laneShape[0].z();
//std::cout << "a) startNode=" << startNode->getID() << " z=" << startNode->getPosition().z() << " oldZ=" << laneShape[0].z() << " cutZ=" << ns[0].z() << " delta=" << delta << "\n";
if (fabs(delta) > 2 * POSITION_EPS && (!startNode->geometryLike() || pb < 1)) {
// make "real" intersections and small intersections flat
//std::cout << "a) startNode=" << startNode->getID() << " z=" << startNode->getPosition().z() << " oldZ=" << laneShape[0].z() << " cutZ=" << ns[0].z() << " delta=" << delta << "\n";
ns[0].setz(startNode->getPosition().z());
}
assert(ns.size() >= 2);
return ns;
} else if (nodeShape.intersects(lb)) {
// extension of first segment intersects
std::vector<double> pbv = lb.intersectsAtLengths2D(nodeShape);
assert(pbv.size() > 0);
double pb = VectorHelper<double>::maxValue(pbv);
assert(pb >= 0);
PositionVector result = laneShape.getSubpartByIndex(1, (int)laneShape.size() - 1);
Position np = lb.positionAtOffset2D(pb);
const double delta = np.z() - laneShape[0].z();
//std::cout << "b) startNode=" << startNode->getID() << " z=" << startNode->getPosition().z() << " oldZ=" << laneShape[0].z() << " cutZ=" << np.z() << " delta=" << delta << "\n";
if (fabs(delta) > 2 * POSITION_EPS && !startNode->geometryLike()) {
// avoid z-overshoot when extrapolating
//std::cout << "b) startNode=" << startNode->getID() << " z=" << startNode->getPosition().z() << " oldZ=" << laneShape[0].z() << " cutZ=" << np.z() << " delta=" << delta << "\n";
np.setz(startNode->getPosition().z());
}
result.push_front_noDoublePos(np);
return result;
//if (result.size() >= 2) {
// return result;
//} else {
// WRITE_WARNING(error + " (resulting shape is too short)");
// return laneShape;
//}
} else {
// could not find proper intersection. Probably the edge is very short
// and lies within nodeShape
// @todo enable warning WRITE_WARNING(error + " (laneShape lies within nodeShape)");
return laneShape;
}
}
const PositionVector&
NBEdge::getLaneShape(int i) const {
return myLanes[i].shape;
}
void
NBEdge::setLaneSpreadFunction(LaneSpreadFunction spread) {
myLaneSpreadFunction = spread;
}
LaneSpreadFunction
NBEdge::getLaneSpreadFunction() const {
return myLaneSpreadFunction;
}
void
NBEdge::addGeometryPoint(int index, const Position& p) {
if (index >= 0) {
myGeom.insert(myGeom.begin() + index, p);
} else {
myGeom.insert(myGeom.end() + index, p);
}
}
void
NBEdge::reduceGeometry(const double minDist) {
// attempt symmetrical removal for forward and backward direction
// (very important for bidiRail)
if (myFrom->getID() < myTo->getID()) {
PositionVector reverse = myGeom.reverse();
reverse.removeDoublePoints(minDist, true, 0, 0, true);
myGeom = reverse.reverse();
for (Lane& lane : myLanes) {
reverse = lane.customShape.reverse();
reverse.removeDoublePoints(minDist, true, 0, 0, true);
lane.customShape = reverse.reverse();
}
} else {
myGeom.removeDoublePoints(minDist, true, 0, 0, true);
for (Lane& lane : myLanes) {
lane.customShape.removeDoublePoints(minDist, true, 0, 0, true);
}
}