-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
MSBaseVehicle.cpp
2426 lines (2196 loc) · 92.8 KB
/
MSBaseVehicle.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 MSBaseVehicle.cpp
/// @author Michael Behrisch
/// @author Daniel Krajzewicz
/// @author Jakob Erdmann
/// @date Mon, 8 Nov 2010
///
// A base class for vehicle implementations
/****************************************************************************/
#include <config.h>
#include <iostream>
#include <cassert>
#include <utils/common/StdDefs.h>
#include <utils/common/MsgHandler.h>
#include <utils/options/OptionsCont.h>
#include <utils/iodevices/OutputDevice.h>
#include <utils/emissions/PollutantsInterface.h>
#include <utils/emissions/HelpersHarmonoise.h>
#include <libsumo/TraCIConstants.h>
#include <mesosim/MELoop.h>
#include <mesosim/MEVehicle.h>
#include <microsim/devices/MSRoutingEngine.h>
#include <microsim/devices/MSDevice_Transportable.h>
#include <microsim/devices/MSDevice_Emissions.h>
#include <microsim/devices/MSDevice_Battery.h>
#include <microsim/devices/MSDevice_ElecHybrid.h>
#include <microsim/devices/MSDevice_Taxi.h>
#include <microsim/devices/MSDevice_Routing.h>
#include <microsim/lcmodels/MSAbstractLaneChangeModel.h>
#include <microsim/transportables/MSPerson.h>
#include <microsim/transportables/MSStageDriving.h>
#include "MSGlobals.h"
#include "MSVehicleControl.h"
#include "MSVehicleType.h"
#include "MSEdge.h"
#include "MSLane.h"
#include "MSMoveReminder.h"
#include "MSEdgeWeightsStorage.h"
#include "MSNet.h"
#include "MSStop.h"
#include "MSParkingArea.h"
#include "MSInsertionControl.h"
#include "MSBaseVehicle.h"
//#define DEBUG_REROUTE
//#define DEBUG_ADD_STOP
//#define DEBUG_COND (getID() == "")
//#define DEBUG_COND (true)
//#define DEBUG_REPLACE_ROUTE
#define DEBUG_COND (isSelected())
// ===========================================================================
// static members
// ===========================================================================
const SUMOTime MSBaseVehicle::NOT_YET_DEPARTED = SUMOTime_MAX;
std::vector<MSTransportable*> MSBaseVehicle::myEmptyTransportableVector;
#ifdef _DEBUG
std::set<std::string> MSBaseVehicle::myShallTraceMoveReminders;
#endif
SUMOTrafficObject::NumericalID MSBaseVehicle::myCurrentNumericalIndex = 0;
// ===========================================================================
// Influencer method definitions
// ===========================================================================
MSBaseVehicle::BaseInfluencer::BaseInfluencer()
{}
// ===========================================================================
// method definitions
// ===========================================================================
double
MSBaseVehicle::getPreviousSpeed() const {
throw ProcessError("getPreviousSpeed() is not available for non-MSVehicles.");
}
MSBaseVehicle::MSBaseVehicle(SUMOVehicleParameter* pars, ConstMSRoutePtr route,
MSVehicleType* type, const double speedFactor) :
SUMOVehicle(pars->id),
myParameter(pars),
myRoute(route),
myType(type),
myCurrEdge(route->begin()),
myChosenSpeedFactor(pars->speedFactor < 0 ? speedFactor : pars->speedFactor),
myMoveReminders(0),
myPersonDevice(nullptr),
myContainerDevice(nullptr),
myEnergyParams(nullptr),
myDeparture(NOT_YET_DEPARTED),
myDepartPos(-1),
myArrivalPos(-1),
myArrivalLane(-1),
myNumberReroutes(0),
myStopUntilOffset(0),
myOdometer(0.),
myRouteValidity(ROUTE_UNCHECKED),
myRoutingMode(libsumo::ROUTING_MODE_DEFAULT),
myNumericalID(myCurrentNumericalIndex++),
myEdgeWeights(nullptr)
#ifdef _DEBUG
, myTraceMoveReminders(myShallTraceMoveReminders.count(pars->id) > 0)
#endif
{
if ((*myRoute->begin())->isTazConnector() || myRoute->getLastEdge()->isTazConnector()) {
pars->parametersSet |= VEHPARS_FORCE_REROUTE;
}
if ((pars->parametersSet & VEHPARS_FORCE_REROUTE) == 0) {
setDepartAndArrivalEdge();
}
if (!pars->wasSet(VEHPARS_FORCE_REROUTE)) {
calculateArrivalParams(true);
}
initTransientModelParams();
}
MSBaseVehicle::~MSBaseVehicle() {
delete myEdgeWeights;
if (myParameter->repetitionNumber == -1) {
// this is not a flow (flows call checkDist in MSInsertionControl::determineCandidates)
MSRoute::checkDist(myParameter->routeid);
}
for (MSVehicleDevice* dev : myDevices) {
delete dev;
}
delete myEnergyParams;
delete myParkingMemory;
checkRouteRemoval();
delete myParameter;
}
void
MSBaseVehicle::checkRouteRemoval() {
// the check for an instance is needed for the unit tests which do not construct a network
// TODO Optimize for speed and there should be a better way to check whether a vehicle is part of a flow
if (MSNet::hasInstance() && !MSNet::getInstance()->hasFlow(getFlowID())) {
myRoute->checkRemoval();
}
}
std::string
MSBaseVehicle::getFlowID() const {
return getID().substr(0, getID().rfind('.'));
}
void
MSBaseVehicle::initDevices() {
MSDevice::buildVehicleDevices(*this, myDevices);
for (MSVehicleDevice* dev : myDevices) {
myMoveReminders.push_back(std::make_pair(dev, 0.));
}
if (MSGlobals::gHaveEmissions) {
// ensure we have the emission parameters even if we don't have the device
getEmissionParameters();
}
}
void
MSBaseVehicle::setID(const std::string& /*newID*/) {
throw ProcessError(TL("Changing a vehicle ID is not permitted"));
}
const SUMOVehicleParameter&
MSBaseVehicle::getParameter() const {
return *myParameter;
}
void
MSBaseVehicle::replaceParameter(const SUMOVehicleParameter* newParameter) {
delete myParameter;
myParameter = newParameter;
}
bool
MSBaseVehicle::ignoreTransientPermissions() const {
return (getRoutingMode() & libsumo::ROUTING_MODE_IGNORE_TRANSIENT_PERMISSIONS) != 0;
}
double
MSBaseVehicle::getMaxSpeed() const {
return MIN2(myType->getMaxSpeed(), myType->getDesiredMaxSpeed() * myChosenSpeedFactor);
}
const MSEdge*
MSBaseVehicle::succEdge(int nSuccs) const {
if (myCurrEdge + nSuccs < myRoute->end() && std::distance(myCurrEdge, myRoute->begin()) <= nSuccs) {
return *(myCurrEdge + nSuccs);
} else {
return nullptr;
}
}
const MSEdge*
MSBaseVehicle::getEdge() const {
return *myCurrEdge;
}
const std::set<SUMOTrafficObject::NumericalID>
MSBaseVehicle::getUpcomingEdgeIDs() const {
std::set<SUMOTrafficObject::NumericalID> result;
for (auto e = myCurrEdge; e != myRoute->end(); ++e) {
result.insert((*e)->getNumericalID());
}
return result;
}
bool
MSBaseVehicle::stopsAt(MSStoppingPlace* stop) const {
if (stop == nullptr) {
return false;
}
for (const MSStop& s : myStops) {
if (s.busstop == stop
|| s.containerstop == stop
|| s.parkingarea == stop
|| s.chargingStation == stop) {
return true;
}
}
return false;
}
bool
MSBaseVehicle::stopsAtEdge(const MSEdge* edge) const {
for (const MSStop& s : myStops) {
if (&s.lane->getEdge() == edge) {
return true;
}
}
return myRoute->getLastEdge() == edge;
}
void
MSBaseVehicle::reroute(SUMOTime t, const std::string& info, SUMOAbstractRouter<MSEdge, SUMOVehicle>& router, const bool onInit, const bool withTaz, const bool silent) {
// check whether to reroute
const MSEdge* source = withTaz && onInit ? MSEdge::dictionary(myParameter->fromTaz + "-source") : *getRerouteOrigin();
if (source == nullptr) {
source = *getRerouteOrigin();
}
const MSEdge* sink = withTaz ? MSEdge::dictionary(myParameter->toTaz + "-sink") : myRoute->getLastEdge();
if (sink == nullptr) {
sink = myRoute->getLastEdge();
}
ConstMSEdgeVector oldEdgesRemaining(source == *myCurrEdge ? myCurrEdge : myCurrEdge + 1, myRoute->end());
ConstMSEdgeVector edges;
ConstMSEdgeVector stops;
std::set<int> jumps;
if (myParameter->via.size() == 0) {
double firstPos = -1;
double lastPos = -1;
stops = getStopEdges(firstPos, lastPos, jumps);
if (stops.size() > 0) {
const double sourcePos = onInit ? 0 : getPositionOnLane();
// avoid superfluous waypoints for first and last edge
const bool skipFirst = stops.front() == source && (source != getEdge() || sourcePos + getBrakeGap() <= firstPos + NUMERICAL_EPS);
const bool skipLast = stops.back() == sink && myArrivalPos >= lastPos && (
stops.size() < 2 || stops.back() != stops[stops.size() - 2]);
#ifdef DEBUG_REROUTE
if (DEBUG_COND) {
std::cout << SIMTIME << " reroute " << info << " veh=" << getID() << " lane=" << Named::getIDSecure(getLane())
<< " source=" << source->getID() << " sourcePos=" << sourcePos << " firstPos=" << firstPos << " arrivalPos=" << myArrivalPos << " lastPos=" << lastPos
<< " route=" << toString(myRoute->getEdges()) << " stopEdges=" << toString(stops) << " skipFirst=" << skipFirst << " skipLast=" << skipLast << "\n";
}
#endif
if (stops.size() == 1 && (skipFirst || skipLast)) {
stops.clear();
} else {
if (skipFirst) {
stops.erase(stops.begin());
}
if (skipLast) {
stops.erase(stops.end() - 1);
}
}
}
} else {
std::set<const MSEdge*> jumpEdges;
for (const MSStop& stop : myStops) {
if (stop.pars.jump >= 0) {
jumpEdges.insert(*stop.edge);
}
}
// via takes precedence over stop edges
// there is a consistency check in MSRouteHandler::addStop that warns when a stop edge is not part of the via edges
for (std::vector<std::string>::const_iterator it = myParameter->via.begin(); it != myParameter->via.end(); ++it) {
MSEdge* viaEdge = MSEdge::dictionary(*it);
if ((viaEdge == source && it == myParameter->via.begin()) || (viaEdge == sink && myParameter->via.end() - it == 1)) {
continue;
}
assert(viaEdge != 0);
if (!viaEdge->isTazConnector() && viaEdge->allowedLanes(getVClass()) == nullptr) {
throw ProcessError(TLF("Vehicle '%' is not allowed on any lane of via edge '%'.", getID(), viaEdge->getID()));
}
stops.push_back(viaEdge);
if (jumpEdges.count(viaEdge) != 0) {
jumps.insert((int)stops.size());
}
}
}
int stopIndex = -1;
for (const MSEdge* const stopEdge : stops) {
stopIndex++;
// !!! need to adapt t here
ConstMSEdgeVector into;
if (jumps.count(stopIndex) != 0) {
edges.push_back(source);
source = stopEdge;
continue;
}
router.computeLooped(source, stopEdge, this, t, into, silent);
//std::cout << SIMTIME << " reroute veh=" << getID() << " source=" << source->getID() << " target=" << (*s)->getID() << " edges=" << toString(into) << "\n";
if (into.size() > 0) {
into.pop_back();
edges.insert(edges.end(), into.begin(), into.end());
if (stopEdge->isTazConnector()) {
source = into.back();
edges.pop_back();
} else {
source = stopEdge;
}
} else {
std::string error = TLF("Vehicle '%' has no valid route from edge '%' to stop edge '%'.", getID(), source->getID(), stopEdge->getID());
if (MSGlobals::gCheckRoutes || silent) {
throw ProcessError(error);
} else {
WRITE_WARNING(error);
edges.push_back(source);
}
source = stopEdge;
}
}
if (stops.empty() && source == sink && onInit
&& myParameter->departPosProcedure == DepartPosDefinition::GIVEN
&& myParameter->arrivalPosProcedure == ArrivalPosDefinition::GIVEN
&& myParameter->departPos > myParameter->arrivalPos) {
router.computeLooped(source, sink, this, t, edges, silent);
} else {
if (!router.compute(source, sink, this, t, edges, silent)) {
edges.clear();
}
}
// router.setHint(myCurrEdge, myRoute->end(), this, t);
if (edges.empty() && silent) {
return;
}
if (!edges.empty() && edges.front()->isTazConnector()) {
edges.erase(edges.begin());
}
if (!edges.empty() && edges.back()->isTazConnector()) {
edges.pop_back();
}
const double routeCost = router.recomputeCosts(edges, this, t);
const double previousCost = onInit ? routeCost : router.recomputeCosts(oldEdgesRemaining, this, t);
const double savings = previousCost - routeCost;
//if (getID() == "43") std::cout << SIMTIME << " pCost=" << previousCost << " cost=" << routeCost
// << " onInit=" << onInit
// << " prevEdges=" << toString(oldEdgesRemaining)
// << " newEdges=" << toString(edges)
// << "\n";
replaceRouteEdges(edges, routeCost, savings, info, onInit);
// this must be called even if the route could not be replaced
if (onInit) {
if (edges.empty()) {
if (MSGlobals::gCheckRoutes) {
throw ProcessError(TLF("Vehicle '%' has no valid route.", getID()));
} else if (source->isTazConnector()) {
WRITE_WARNINGF(TL("Removing vehicle '%' which has no valid route."), getID());
MSNet::getInstance()->getInsertionControl().descheduleDeparture(this);
return;
}
}
setDepartAndArrivalEdge();
calculateArrivalParams(onInit);
}
}
bool
MSBaseVehicle::replaceRouteEdges(ConstMSEdgeVector& edges, double cost, double savings, const std::string& info, bool onInit, bool check, bool removeStops, std::string* msgReturn) {
if (edges.empty()) {
WRITE_WARNINGF(TL("No route for vehicle '%' found."), getID());
if (msgReturn != nullptr) {
*msgReturn = "No route found";
}
return false;
}
// build a new id, first
std::string id = getID();
if (id[0] != '!') {
id = "!" + id;
}
const std::string idSuffix = id + "!var#";
int varIndex = 1;
id = idSuffix + toString(varIndex);
while (MSRoute::hasRoute(id)) {
id = idSuffix + toString(++varIndex);
}
int oldSize = (int)edges.size();
if (!onInit) {
const MSEdge* const origin = *getRerouteOrigin();
if (origin != *myCurrEdge && edges.front() == origin) {
edges.insert(edges.begin(), *myCurrEdge);
oldSize = (int)edges.size();
}
edges.insert(edges.begin(), myRoute->begin(), myCurrEdge);
}
if (edges == myRoute->getEdges() && haveValidStopEdges(true)) {
// re-assign stop iterators when rerouting to a new parkingArea / insertStop
return true;
}
const RGBColor& c = myRoute->getColor();
MSRoute* newRoute = new MSRoute(id, edges, false, &c == &RGBColor::DEFAULT_COLOR ? nullptr : new RGBColor(c), std::vector<SUMOVehicleParameter::Stop>());
newRoute->setCosts(cost);
newRoute->setSavings(savings);
ConstMSRoutePtr constRoute = std::shared_ptr<MSRoute>(newRoute);
if (!MSRoute::dictionary(id, constRoute)) {
delete newRoute;
if (msgReturn != nullptr) {
*msgReturn = "duplicate routeID '" + id + "'";
}
return false;
}
std::string msg;
if (check && !hasValidRoute(msg, constRoute)) {
WRITE_WARNINGF(TL("Invalid route replacement for vehicle '%'. %"), getID(), msg);
if (MSGlobals::gCheckRoutes) {
if (msgReturn != nullptr) {
*msgReturn = msg;
}
return false;
}
}
if (!replaceRoute(constRoute, info, onInit, (int)edges.size() - oldSize, false, removeStops, msgReturn)) {
return false;
}
return true;
}
bool
MSBaseVehicle::replaceRoute(ConstMSRoutePtr newRoute, const std::string& info, bool onInit, int offset, bool addRouteStops, bool removeStops, std::string* msgReturn) {
const ConstMSEdgeVector& edges = newRoute->getEdges();
// rebuild in-vehicle route information
if (onInit) {
myCurrEdge = newRoute->begin();
} else {
MSRouteIterator newCurrEdge = std::find(edges.begin() + offset, edges.end(), *myCurrEdge);
if (newCurrEdge == edges.end()) {
if (msgReturn != nullptr) {
*msgReturn = TLF("current edge '%' not found in new route", (*myCurrEdge)->getID());
}
#ifdef DEBUG_REPLACE_ROUTE
if (DEBUG_COND) {
std::cout << " newCurrEdge not found\n";
}
#endif
return false;
}
if (getLane() != nullptr) {
if (getLane()->getEdge().isInternal() && (
(newCurrEdge + 1) == edges.end() || (*(newCurrEdge + 1)) != &(getLane()->getOutgoingViaLanes().front().first->getEdge()))) {
if (msgReturn != nullptr) {
*msgReturn = TL("Vehicle is on junction-internal edge leading elsewhere");
}
#ifdef DEBUG_REPLACE_ROUTE
if (DEBUG_COND) {
std::cout << " Vehicle is on junction-internal edge leading elsewhere\n";
}
#endif
return false;
} else if (getPositionOnLane() > getLane()->getLength()
&& (myCurrEdge + 1) != myRoute->end()
&& (newCurrEdge + 1) != edges.end()
&& *(myCurrEdge + 1) != *(newCurrEdge + 1)) {
if (msgReturn != nullptr) {
*msgReturn = TL("Vehicle is moving past junction and committed to move to another successor edge");
}
#ifdef DEBUG_REPLACE_ROUTE
if (DEBUG_COND) {
std::cout << " Vehicle is moving past junction and committed to move to another successor edge\n";
}
#endif
return false;
}
}
myCurrEdge = newCurrEdge;
}
const bool stopsFromScratch = onInit && myRoute->getStops().empty();
// assign new route
checkRouteRemoval();
myRoute = newRoute;
// update arrival definition
calculateArrivalParams(onInit);
// save information that the vehicle was rerouted
myNumberReroutes++;
myStopUntilOffset += myRoute->getPeriod();
MSNet::getInstance()->informVehicleStateListener(this, MSNet::VehicleState::NEWROUTE, info);
#ifdef DEBUG_REPLACE_ROUTE
if (DEBUG_COND) {
std::cout << SIMTIME << " replaceRoute info=" << info << " on " << (*myCurrEdge)->getID()
<< " lane=" << Named::getIDSecure(getLane())
<< " stopsFromScratch=" << stopsFromScratch
<< " newSize=" << newRoute->getEdges().size()
<< " newIndex=" << (myCurrEdge - newRoute->begin())
<< " edges=" << toString(newRoute->getEdges())
<< "\n";
}
#endif
// if we did not drive yet it may be best to simply reassign the stops from scratch
if (stopsFromScratch) {
myStops.clear();
addStops(!MSGlobals::gCheckRoutes);
} else {
// recheck old stops
MSRouteIterator searchStart = myCurrEdge;
double lastPos = getPositionOnLane() + getBrakeGap();
if (getLane() != nullptr && getLane()->isInternal()
&& myStops.size() > 0 && !myStops.front().lane->isInternal()) {
// searchStart is still incoming to the intersection so lastPos
// relative to that edge must be adapted
lastPos += (*myCurrEdge)->getLength();
}
for (std::list<MSStop>::iterator iter = myStops.begin(); iter != myStops.end();) {
double endPos = iter->getEndPos(*this);
#ifdef DEBUG_REPLACE_ROUTE
if (DEBUG_COND) {
std::cout << " stopEdge=" << iter->lane->getEdge().getID() << " start=" << (searchStart - myCurrEdge) << " endPos=" << endPos << " lastPos=" << lastPos << "\n";
}
#endif
if (*searchStart != &iter->lane->getEdge()
|| endPos + NUMERICAL_EPS < lastPos) {
if (searchStart != edges.end() && !iter->reached) {
searchStart++;
}
}
lastPos = endPos;
iter->edge = std::find(searchStart, edges.end(), &iter->lane->getEdge());
#ifdef DEBUG_REPLACE_ROUTE
if (DEBUG_COND) {
std::cout << " foundIndex=" << (iter->edge - myCurrEdge) << " end=" << (edges.end() - myCurrEdge) << "\n";
}
#endif
if (iter->edge == edges.end()) {
if (!removeStops) {
WRITE_ERRORF(TL("Vehicle '%' could not assign stop '%' after rerouting (%) at time=%."), getID(), iter->getDescription(), info, time2string(SIMSTEP));
}
iter = myStops.erase(iter);
continue;
} else {
searchStart = iter->edge;
}
++iter;
}
// add new stops
if (addRouteStops) {
for (std::vector<SUMOVehicleParameter::Stop>::const_iterator i = newRoute->getStops().begin(); i != newRoute->getStops().end(); ++i) {
std::string error;
addStop(*i, error, myParameter->depart + myStopUntilOffset);
if (error != "") {
WRITE_WARNING(error);
}
}
}
}
return true;
}
double
MSBaseVehicle::getAcceleration() const {
return 0;
}
void
MSBaseVehicle::onDepart() {
myDeparture = MSNet::getInstance()->getCurrentTimeStep();
myDepartPos = getPositionOnLane();
MSNet::getInstance()->getVehicleControl().vehicleDeparted(*this);
}
SUMOTime
MSBaseVehicle:: getDepartDelay() const {
const SUMOTime dep = getParameter().depart;
if (dep < 0) {
return 0;
}
return hasDeparted() ? getDeparture() - dep : SIMSTEP - dep;
}
bool
MSBaseVehicle::hasArrived() const {
return succEdge(1) == nullptr;
}
int
MSBaseVehicle::getRoutePosition() const {
return (int) std::distance(myRoute->begin(), myCurrEdge);
}
void
MSBaseVehicle::resetRoutePosition(int index, DepartLaneDefinition departLaneProcedure) {
myCurrEdge = myRoute->begin() + index;
const_cast<SUMOVehicleParameter*>(myParameter)->departLaneProcedure = departLaneProcedure;
// !!! hack
myArrivalPos = (*(myRoute->end() - 1))->getLanes()[0]->getLength();
}
double
MSBaseVehicle::getOdometer() const {
return -myDepartPos + myOdometer + (hasArrived() ? myArrivalPos : getPositionOnLane());
}
bool
MSBaseVehicle::allowsBoarding(const MSTransportable* t) const {
if (t->isPerson() && getPersonNumber() >= getVehicleType().getPersonCapacity()) {
return false;
} else if (!t->isPerson() && getContainerNumber() >= getVehicleType().getContainerCapacity()) {
return false;
}
if (isStopped() && myStops.begin()->pars.permitted.size() > 0
&& myStops.begin()->pars.permitted.count(t->getID()) == 0) {
return false;
}
MSDevice_Taxi* taxiDevice = static_cast<MSDevice_Taxi*>(getDevice(typeid(MSDevice_Taxi)));
if (taxiDevice != nullptr) {
return taxiDevice->allowsBoarding(t);
}
return true;
}
void
MSBaseVehicle::addTransportable(MSTransportable* transportable) {
if (transportable->isPerson()) {
if (myPersonDevice == nullptr) {
myPersonDevice = MSDevice_Transportable::buildVehicleDevices(*this, myDevices, false);
myMoveReminders.push_back(std::make_pair(myPersonDevice, 0.));
if (myParameter->departProcedure == DepartDefinition::TRIGGERED && myParameter->depart == -1) {
const_cast<SUMOVehicleParameter*>(myParameter)->depart = MSNet::getInstance()->getCurrentTimeStep();
}
}
myPersonDevice->addTransportable(transportable);
} else {
if (myContainerDevice == nullptr) {
myContainerDevice = MSDevice_Transportable::buildVehicleDevices(*this, myDevices, true);
myMoveReminders.push_back(std::make_pair(myContainerDevice, 0.));
if (myParameter->departProcedure == DepartDefinition::CONTAINER_TRIGGERED && myParameter->depart == -1) {
const_cast<SUMOVehicleParameter*>(myParameter)->depart = MSNet::getInstance()->getCurrentTimeStep();
}
}
myContainerDevice->addTransportable(transportable);
}
}
bool
MSBaseVehicle::hasJump(const MSRouteIterator& it) const {
for (const MSStop& stop : myStops) {
if (stop.edge == it) {
return stop.pars.jump >= 0;
}
}
return false;
}
bool
MSBaseVehicle::hasValidRoute(std::string& msg, ConstMSRoutePtr route) const {
MSRouteIterator start = myCurrEdge;
if (route == nullptr) {
route = myRoute;
} else {
start = route->begin();
}
const bool checkJumps = route == myRoute; // the edge iterators in the stops are invalid otherwise
MSRouteIterator last = route->end() - 1;
// check connectivity, first
for (MSRouteIterator e = start; e != last; ++e) {
const MSEdge& next = **(e + 1);
if ((*e)->allowedLanes(next, myType->getVehicleClass()) == nullptr) {
if (!checkJumps || !hasJump(e)) {
if ((myRoutingMode & libsumo::ROUTING_MODE_IGNORE_TRANSIENT_PERMISSIONS) == 0
|| (!next.hasTransientPermissions() && !(*e)->hasTransientPermissions())) {
msg = TLF("No connection between edge '%' and edge '%'.", (*e)->getID(), (*(e + 1))->getID());
return false;
}
}
}
}
last = route->end();
// check usable lanes, then
for (MSRouteIterator e = start; e != last; ++e) {
if ((*e)->prohibits(this)) {
msg = TLF("Edge '%' prohibits.", (*e)->getID());
return false;
}
}
return true;
}
bool
MSBaseVehicle::hasValidRouteStart(std::string& msg) {
if (!(*myCurrEdge)->isTazConnector()) {
if (myParameter->departSpeedProcedure == DepartSpeedDefinition::GIVEN && myParameter->departSpeed > myType->getMaxSpeed() + SPEED_EPS) {
msg = TLF("Departure speed for vehicle '%' is too high for the vehicle type '%'.", getID(), myType->getID());
myRouteValidity |= ROUTE_START_INVALID_LANE;
return false;
}
}
if (myRoute->getEdges().size() > 0 && !(*myCurrEdge)->prohibits(this)) {
myRouteValidity &= ~ROUTE_START_INVALID_PERMISSIONS;
return true;
} else {
msg = TLF("Vehicle '%' is not allowed to depart on any lane of edge '%'.", getID(), (*myCurrEdge)->getID());
myRouteValidity |= ROUTE_START_INVALID_PERMISSIONS;
return false;
}
}
int
MSBaseVehicle::getRouteValidity(bool update, bool silent, std::string* msgReturn) {
if (!update) {
return myRouteValidity;
}
// insertion check must be done in any case
std::string msg;
if (!hasValidRouteStart(msg)) {
if (MSGlobals::gCheckRoutes) {
throw ProcessError(msg);
} else if (!silent) {
// vehicle will be discarded
WRITE_WARNING(msg);
} else if (msgReturn != nullptr) {
*msgReturn = msg;
}
}
if (MSGlobals::gCheckRoutes
&& (myRouteValidity & ROUTE_UNCHECKED) != 0
// we could check after the first rerouting
&& (!myParameter->wasSet(VEHPARS_FORCE_REROUTE))) {
if (!hasValidRoute(msg, myRoute)) {
myRouteValidity |= ROUTE_INVALID;
throw ProcessError(TLF("Vehicle '%' has no valid route. %", getID(), msg));
}
}
myRouteValidity &= ~ROUTE_UNCHECKED;
return myRouteValidity;
}
void
MSBaseVehicle::addReminder(MSMoveReminder* rem) {
#ifdef _DEBUG
if (myTraceMoveReminders) {
traceMoveReminder("add", rem, 0, true);
}
#endif
myMoveReminders.push_back(std::make_pair(rem, 0.));
}
void
MSBaseVehicle::removeReminder(MSMoveReminder* rem) {
for (MoveReminderCont::iterator r = myMoveReminders.begin(); r != myMoveReminders.end(); ++r) {
if (r->first == rem) {
#ifdef _DEBUG
if (myTraceMoveReminders) {
traceMoveReminder("remove", rem, 0, false);
}
#endif
myMoveReminders.erase(r);
return;
}
}
}
void
MSBaseVehicle::activateReminders(const MSMoveReminder::Notification reason, const MSLane* enteredLane) {
for (MoveReminderCont::iterator rem = myMoveReminders.begin(); rem != myMoveReminders.end();) {
if (rem->first->notifyEnter(*this, reason, enteredLane)) {
#ifdef _DEBUG
if (myTraceMoveReminders) {
traceMoveReminder("notifyEnter", rem->first, rem->second, true);
}
#endif
++rem;
} else {
#ifdef _DEBUG
if (myTraceMoveReminders) {
traceMoveReminder("notifyEnter", rem->first, rem->second, false);
}
#endif
rem = myMoveReminders.erase(rem);
}
}
}
void
MSBaseVehicle::calculateArrivalParams(bool onInit) {
if (myRoute->getLastEdge()->isTazConnector()) {
return;
}
const int arrivalEdgeIndex = MIN2(myParameter->arrivalEdge, (int)myRoute->getEdges().size() - 1);
if (arrivalEdgeIndex != myParameter->arrivalEdge) {
WRITE_WARNINGF(TL("Vehicle '%' ignores attribute arrivalEdge=% after rerouting at time=% (routeLength=%)"),
getID(), myParameter->arrivalEdge, time2string(SIMSTEP), myRoute->getEdges().size() - 1);
}
const MSEdge* arrivalEdge = myParameter->arrivalEdge >= 0 ? myRoute->getEdges()[arrivalEdgeIndex] : myRoute->getLastEdge();
if (!onInit) {
arrivalEdge = myRoute->getLastEdge();
// ignore arrivalEdge parameter after rerouting
const_cast<SUMOVehicleParameter*>(myParameter)->arrivalEdge = -1;
}
const std::vector<MSLane*>& lanes = arrivalEdge->getLanes();
const double lastLaneLength = lanes[0]->getLength();
switch (myParameter->arrivalPosProcedure) {
case ArrivalPosDefinition::GIVEN:
if (fabs(myParameter->arrivalPos) > lastLaneLength) {
WRITE_WARNINGF(TL("Vehicle '%' will not be able to arrive at the given position!"), getID());
}
// Maybe we should warn the user about invalid inputs!
myArrivalPos = MIN2(myParameter->arrivalPos, lastLaneLength);
if (myArrivalPos < 0) {
myArrivalPos = MAX2(myArrivalPos + lastLaneLength, 0.);
}
break;
case ArrivalPosDefinition::RANDOM:
myArrivalPos = RandHelper::rand(lastLaneLength);
break;
case ArrivalPosDefinition::CENTER:
myArrivalPos = lastLaneLength / 2.;
break;
default:
myArrivalPos = lastLaneLength;
break;
}
if (myParameter->arrivalLaneProcedure == ArrivalLaneDefinition::GIVEN) {
if (myParameter->arrivalLane >= (int)lanes.size() || !lanes[myParameter->arrivalLane]->allowsVehicleClass(myType->getVehicleClass())) {
WRITE_WARNINGF(TL("Vehicle '%' will not be able to arrive at the given lane '%_%'!"), getID(), arrivalEdge->getID(), toString(myParameter->arrivalLane));
}
myArrivalLane = MIN2(myParameter->arrivalLane, (int)(lanes.size() - 1));
} else if (myParameter->arrivalLaneProcedure == ArrivalLaneDefinition::FIRST_ALLOWED) {
myArrivalLane = -1;
for (MSLane* lane : lanes) {
if (lane->allowsVehicleClass(myType->getVehicleClass())) {
myArrivalLane = lane->getIndex();
break;
}
}
if (myArrivalLane == -1) {
WRITE_WARNINGF(TL("Vehicle '%' has no usable arrivalLane on edge '%'."), getID(), arrivalEdge->getID());
myArrivalLane = 0;
}
} else if (myParameter->arrivalLaneProcedure == ArrivalLaneDefinition::RANDOM) {
// pick random lane among all usable lanes
std::vector<MSLane*> usable;
for (MSLane* lane : lanes) {
if (lane->allowsVehicleClass(myType->getVehicleClass())) {
usable.push_back(lane);
}
}
if (usable.empty()) {
WRITE_WARNINGF(TL("Vehicle '%' has no usable arrivalLane on edge '%'."), getID(), arrivalEdge->getID());
myArrivalLane = 0;
} else {
myArrivalLane = usable[RandHelper::rand(0, (int)usable.size())]->getIndex();
}
}
if (myParameter->arrivalSpeedProcedure == ArrivalSpeedDefinition::GIVEN) {
for (std::vector<MSLane*>::const_iterator l = lanes.begin(); l != lanes.end(); ++l) {
if (myParameter->arrivalSpeed <= (*l)->getVehicleMaxSpeed(this)) {
return;
}
}
WRITE_WARNINGF(TL("Vehicle '%' will not be able to arrive with the given speed!"), getID());
}
}
void
MSBaseVehicle::setDepartAndArrivalEdge() {
SUMOVehicleParameter* pars = const_cast<SUMOVehicleParameter*>(myParameter);
if (pars->departEdgeProcedure != RouteIndexDefinition::DEFAULT) {
const int routeEdges = (int)myRoute->getEdges().size();
if (pars->departEdgeProcedure == RouteIndexDefinition::RANDOM) {
// write specific edge in vehroute output for reproducibility
pars->departEdge = RandHelper::rand(0, routeEdges);
pars->departEdgeProcedure = RouteIndexDefinition::GIVEN;
}
assert(pars->departEdge >= 0);
if (pars->departEdge >= routeEdges) {
WRITE_WARNINGF(TL("Ignoring departEdge % for vehicle '%' with % route edges"), toString(pars->departEdge), getID(), toString(routeEdges));
} else {
myCurrEdge += pars->departEdge;
}
}
if (pars->arrivalEdgeProcedure == RouteIndexDefinition::RANDOM) {
const int routeEdges = (int)myRoute->getEdges().size();
const int begin = (int)(myCurrEdge - myRoute->begin());
// write specific edge in vehroute output for reproducibility
pars->arrivalEdge = RandHelper::rand(begin, routeEdges);
pars->arrivalEdgeProcedure = RouteIndexDefinition::GIVEN;
assert(pars->arrivalEdge >= begin);
assert(pars->arrivalEdge < routeEdges);
}
}
double
MSBaseVehicle::getImpatience() const {
return MAX2(0., MIN2(1., getVehicleType().getImpatience()
+ (hasInfluencer() ? getBaseInfluencer()->getExtraImpatience() : 0)
+ (MSGlobals::gTimeToImpatience > 0 ? (double)getWaitingTime() / (double)MSGlobals::gTimeToImpatience : 0.)));
}
MSDevice*
MSBaseVehicle::getDevice(const std::type_info& type) const {
for (MSVehicleDevice* const dev : myDevices) {
if (typeid(*dev) == type) {
return dev;
}
}
return nullptr;
}
void
MSBaseVehicle::saveState(OutputDevice& out) {
// the parameters may hold the name of a vTypeDistribution but we are interested in the actual type
const std::string& typeID = MSNet::getInstance()->getVehicleControl().hasVTypeDistribution(myParameter->vtypeid) || getVehicleType().isVehicleSpecific() ? getVehicleType().getID() : "";
myParameter->write(out, OptionsCont::getOptions(), SUMO_TAG_VEHICLE, typeID);
// params and stops must be written in child classes since they may wish to add additional attributes first
out.writeAttr(SUMO_ATTR_ROUTE, myRoute->getID());
std::ostringstream os;
os << myOdometer << " " << myNumberReroutes;
out.writeAttr(SUMO_ATTR_DISTANCE, os.str());
if (!myParameter->wasSet(VEHPARS_SPEEDFACTOR_SET)) {
const int precision = out.precision();
out.setPrecision(MAX2(gPrecisionRandom, precision));
out.writeAttr(SUMO_ATTR_SPEEDFACTOR, myChosenSpeedFactor);
out.setPrecision(precision);
}
if (myParameter->wasSet(VEHPARS_FORCE_REROUTE)) {
out.writeAttr(SUMO_ATTR_REROUTE, true);
}
if (!myParameter->wasSet(VEHPARS_LINE_SET) && myParameter->line != "") {
// could be set from stop
out.writeAttr(SUMO_ATTR_LINE, myParameter->line);
}
// here starts the vehicle internal part (see loading)
// @note: remember to close the vehicle tag when calling this in a subclass!
}
bool
MSBaseVehicle::handleCollisionStop(MSStop& stop, const double distToStop) {
UNUSED_PARAMETER(stop);
UNUSED_PARAMETER(distToStop);
return true;
}