Eclipse SUMO - Simulation of Urban MObility
Loading...
Searching...
No Matches
MSVehicle.cpp
Go to the documentation of this file.
1/****************************************************************************/
2// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3// Copyright (C) 2001-2026 German Aerospace Center (DLR) and others.
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License 2.0 which is available at
6// https://www.eclipse.org/legal/epl-2.0/
7// This Source Code may also be made available under the following Secondary
8// Licenses when the conditions for such availability set forth in the Eclipse
9// Public License 2.0 are satisfied: GNU General Public License, version 2
10// or later which is available at
11// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
12// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
13/****************************************************************************/
31// Representation of a vehicle in the micro simulation
32/****************************************************************************/
33#include <config.h>
34
35#include <iostream>
36#include <cassert>
37#include <cmath>
38#include <cstdlib>
39#include <algorithm>
40#include <map>
41#include <memory>
72#include "MSEdgeControl.h"
73#include "MSVehicleControl.h"
74#include "MSInsertionControl.h"
75#include "MSVehicleTransfer.h"
76#include "MSGlobals.h"
77#include "MSJunctionLogic.h"
78#include "MSStop.h"
79#include "MSStoppingPlace.h"
80#include "MSParkingArea.h"
81#include "MSMoveReminder.h"
82#include "MSLane.h"
83#include "MSJunction.h"
84#include "MSEdge.h"
85#include "MSVehicleType.h"
86#include "MSNet.h"
87#include "MSRoute.h"
88#include "MSLeaderInfo.h"
89#include "MSDriverState.h"
90#include "MSVehicle.h"
91
92
93//#define DEBUG_PLAN_MOVE
94//#define DEBUG_PLAN_MOVE_LEADERINFO
95//#define DEBUG_CHECKREWINDLINKLANES
96//#define DEBUG_EXEC_MOVE
97//#define DEBUG_FURTHER
98//#define DEBUG_SETFURTHER
99//#define DEBUG_TARGET_LANE
100//#define DEBUG_STOPS
101//#define DEBUG_BESTLANES
102//#define DEBUG_IGNORE_RED
103//#define DEBUG_ACTIONSTEPS
104//#define DEBUG_NEXT_TURN
105//#define DEBUG_TRACI
106//#define DEBUG_REVERSE_BIDI
107//#define DEBUG_EXTRAPOLATE_DEPARTPOS
108//#define DEBUG_REMOTECONTROL
109//#define DEBUG_MOVEREMINDERS
110//#define DEBUG_COND (getID() == "ego")
111//#define DEBUG_COND (true)
112#define DEBUG_COND (isSelected())
113//#define DEBUG_COND2(obj) (obj->getID() == "ego")
114#define DEBUG_COND2(obj) (obj->isSelected())
115
116//#define PARALLEL_STOPWATCH
117
118
119#define STOPPING_PLACE_OFFSET 0.5
120
121#define CRLL_LOOK_AHEAD 5
122
123#define JUNCTION_BLOCKAGE_TIME 5 // s
124
125// @todo Calibrate with real-world values / make configurable
126#define DIST_TO_STOPLINE_EXPECT_PRIORITY 1.0
127
128#define NUMERICAL_EPS_SPEED (0.1 * NUMERICAL_EPS * TS)
129
130// ===========================================================================
131// static value definitions
132// ===========================================================================
133std::vector<MSLane*> MSVehicle::myEmptyLaneVector;
134
135
136// ===========================================================================
137// method definitions
138// ===========================================================================
139/* -------------------------------------------------------------------------
140 * methods of MSVehicle::State
141 * ----------------------------------------------------------------------- */
143 myPos = state.myPos;
144 mySpeed = state.mySpeed;
145 myPosLat = state.myPosLat;
146 myBackPos = state.myBackPos;
149}
150
151
154 myPos = state.myPos;
155 mySpeed = state.mySpeed;
156 myPosLat = state.myPosLat;
157 myBackPos = state.myBackPos;
158 myPreviousSpeed = state.myPreviousSpeed;
159 myLastCoveredDist = state.myLastCoveredDist;
160 return *this;
161}
162
163
164bool
166 return (myPos != state.myPos ||
167 mySpeed != state.mySpeed ||
168 myPosLat != state.myPosLat ||
169 myLastCoveredDist != state.myLastCoveredDist ||
170 myPreviousSpeed != state.myPreviousSpeed ||
171 myBackPos != state.myBackPos);
172}
173
174
175MSVehicle::State::State(double pos, double speed, double posLat, double backPos, double previousSpeed) :
176 myPos(pos), mySpeed(speed), myPosLat(posLat), myBackPos(backPos), myPreviousSpeed(previousSpeed), myLastCoveredDist(SPEED2DIST(speed)) {}
177
178
179
180/* -------------------------------------------------------------------------
181 * methods of MSVehicle::WaitingTimeCollector
182 * ----------------------------------------------------------------------- */
184
185
188 assert(memorySpan <= myMemorySize);
189 if (memorySpan == -1) {
190 memorySpan = myMemorySize;
191 }
192 SUMOTime totalWaitingTime = 0;
193 for (const auto& interval : myWaitingIntervals) {
194 if (interval.second >= memorySpan) {
195 if (interval.first >= memorySpan) {
196 break;
197 } else {
198 totalWaitingTime += memorySpan - interval.first;
199 }
200 } else {
201 totalWaitingTime += interval.second - interval.first;
202 }
203 }
204 return totalWaitingTime;
205}
206
207
208void
210 auto i = myWaitingIntervals.begin();
211 const auto end = myWaitingIntervals.end();
212 const bool startNewInterval = i == end || (i->first != 0);
213 while (i != end) {
214 i->first += dt;
215 if (i->first >= myMemorySize) {
216 break;
217 }
218 i->second += dt;
219 i++;
220 }
221
222 // remove intervals beyond memorySize
223 auto d = std::distance(i, end);
224 while (d > 0) {
225 myWaitingIntervals.pop_back();
226 d--;
227 }
228
229 if (!waiting) {
230 return;
231 } else if (!startNewInterval) {
232 myWaitingIntervals.begin()->first = 0;
233 } else {
234 myWaitingIntervals.push_front(std::make_pair(0, dt));
235 }
236 return;
237}
238
239
240const std::string
242 std::ostringstream state;
243 state << myMemorySize << " " << myWaitingIntervals.size();
244 for (const auto& interval : myWaitingIntervals) {
245 state << " " << interval.first << " " << interval.second;
246 }
247 return state.str();
248}
249
250
251void
253 std::istringstream is(state);
254 int numIntervals;
255 SUMOTime begin, end;
256 is >> myMemorySize >> numIntervals;
257 while (numIntervals-- > 0) {
258 is >> begin >> end;
259 myWaitingIntervals.emplace_back(begin, end);
260 }
261}
262
263
264/* -------------------------------------------------------------------------
265 * methods of MSVehicle::Influencer::GapControlState
266 * ----------------------------------------------------------------------- */
267void
269// std::cout << "GapControlVehStateListener::vehicleStateChanged() vehicle=" << vehicle->getID() << ", to=" << to << std::endl;
270 switch (to) {
274 // Vehicle left road
275// Look up reference vehicle in refVehMap and in case deactivate corresponding gap control
276 const MSVehicle* msVeh = static_cast<const MSVehicle*>(vehicle);
277// std::cout << "GapControlVehStateListener::vehicleStateChanged() vehicle=" << vehicle->getID() << " left the road." << std::endl;
278 if (GapControlState::refVehMap.find(msVeh) != end(GapControlState::refVehMap)) {
279// std::cout << "GapControlVehStateListener::deactivating ref vehicle=" << vehicle->getID() << std::endl;
280 GapControlState::refVehMap[msVeh]->deactivate();
281 }
282 }
283 break;
284 default:
285 {};
286 // do nothing, vehicle still on road
287 }
288}
289
290std::map<const MSVehicle*, MSVehicle::Influencer::GapControlState*>
292
294
296 tauOriginal(-1), tauCurrent(-1), tauTarget(-1), addGapCurrent(-1), addGapTarget(-1),
297 remainingDuration(-1), changeRate(-1), maxDecel(-1), referenceVeh(nullptr), active(false), gapAttained(false), prevLeader(nullptr),
298 lastUpdate(-1), timeHeadwayIncrement(0.0), spaceHeadwayIncrement(0.0) {}
299
300
304
305void
307 if (MSNet::hasInstance()) {
308 if (myVehStateListener == nullptr) {
309 //std::cout << "GapControlState::init()" << std::endl;
310 myVehStateListener = new GapControlVehStateListener();
311 MSNet::getInstance()->addVehicleStateListener(myVehStateListener);
312 }
313 } else {
314 WRITE_ERROR("MSVehicle::Influencer::GapControlState::init(): No MSNet instance found!")
315 }
316}
317
318void
320 if (myVehStateListener != nullptr) {
321 MSNet::getInstance()->removeVehicleStateListener(myVehStateListener);
322 delete myVehStateListener;
323 myVehStateListener = nullptr;
324 }
325}
326
327void
328MSVehicle::Influencer::GapControlState::activate(double tauOrig, double tauNew, double additionalGap, double dur, double rate, double decel, const MSVehicle* refVeh) {
330 WRITE_ERROR(TL("No gap control available for meso."))
331 } else {
332 // always deactivate control before activating (triggers clean-up of refVehMap)
333// std::cout << "activate gap control with refVeh=" << (refVeh==nullptr? "NULL" : refVeh->getID()) << std::endl;
334 tauOriginal = tauOrig;
335 tauCurrent = tauOrig;
336 tauTarget = tauNew;
337 addGapCurrent = 0.0;
338 addGapTarget = additionalGap;
339 remainingDuration = dur;
340 changeRate = rate;
341 maxDecel = decel;
342 referenceVeh = refVeh;
343 active = true;
344 gapAttained = false;
345 prevLeader = nullptr;
346 lastUpdate = SIMSTEP - DELTA_T;
347 timeHeadwayIncrement = changeRate * TS * (tauTarget - tauOriginal);
348 spaceHeadwayIncrement = changeRate * TS * addGapTarget;
349
350 if (referenceVeh != nullptr) {
351 // Add refVeh to refVehMap
352 GapControlState::refVehMap[referenceVeh] = this;
353 }
354 }
355}
356
357void
359 active = false;
360 if (referenceVeh != nullptr) {
361 // Remove corresponding refVehMapEntry if appropriate
362 GapControlState::refVehMap.erase(referenceVeh);
363 referenceVeh = nullptr;
364 }
365}
366
367
368/* -------------------------------------------------------------------------
369 * methods of MSVehicle::Influencer
370 * ----------------------------------------------------------------------- */
392
393
395
396void
398 GapControlState::init();
399}
400
401void
403 GapControlState::cleanup();
404}
405
406void
407MSVehicle::Influencer::setSpeedTimeLine(const std::vector<std::pair<SUMOTime, double> >& speedTimeLine) {
408 mySpeedAdaptationStarted = true;
409 mySpeedTimeLine = speedTimeLine;
410}
411
412void
413MSVehicle::Influencer::activateGapController(double originalTau, double newTimeHeadway, double newSpaceHeadway, double duration, double changeRate, double maxDecel, MSVehicle* refVeh) {
414 if (myGapControlState == nullptr) {
415 myGapControlState = std::make_shared<GapControlState>();
416 init(); // only does things on first call
417 }
418 myGapControlState->activate(originalTau, newTimeHeadway, newSpaceHeadway, duration, changeRate, maxDecel, refVeh);
419}
420
421void
423 if (myGapControlState != nullptr && myGapControlState->active) {
424 myGapControlState->deactivate();
425 }
426}
427
428void
429MSVehicle::Influencer::setLaneTimeLine(const std::vector<std::pair<SUMOTime, int> >& laneTimeLine) {
430 myLaneTimeLine = laneTimeLine;
431}
432
433
434void
436 for (auto& item : myLaneTimeLine) {
437 item.second += indexShift;
438 }
439}
440
441
442void
444 myLatDist = latDist;
445}
446
447int
449 return (1 * myConsiderSafeVelocity +
450 2 * myConsiderMaxAcceleration +
451 4 * myConsiderMaxDeceleration +
452 8 * myRespectJunctionPriority +
453 16 * myEmergencyBrakeRedLight +
454 32 * !myRespectJunctionLeaderPriority + // inverted!
455 64 * !myConsiderSpeedLimit // inverted!
456 );
457}
458
459
460int
462 return (1 * myStrategicLC +
463 4 * myCooperativeLC +
464 16 * mySpeedGainLC +
465 64 * myRightDriveLC +
466 256 * myTraciLaneChangePriority +
467 1024 * mySublaneLC);
468}
469
472 SUMOTime duration = -1;
473 for (std::vector<std::pair<SUMOTime, int>>::iterator i = myLaneTimeLine.begin(); i != myLaneTimeLine.end(); ++i) {
474 if (duration < 0) {
475 duration = i->first;
476 } else {
477 duration -= i->first;
478 }
479 }
480 return -duration;
481}
482
485 if (!myLaneTimeLine.empty()) {
486 return myLaneTimeLine.back().first;
487 } else {
488 return -1;
489 }
490}
491
492
493double
494MSVehicle::Influencer::influenceSpeed(SUMOTime currentTime, double speed, double vSafe, double vMin, double vMax) {
495 // remove leading commands which are no longer valid
496 while (mySpeedTimeLine.size() == 1 || (mySpeedTimeLine.size() > 1 && currentTime > mySpeedTimeLine[1].first)) {
497 mySpeedTimeLine.erase(mySpeedTimeLine.begin());
498 }
499
500 if (!(mySpeedTimeLine.size() < 2 || currentTime < mySpeedTimeLine[0].first)) {
501 // Speed advice is active -> compute new speed according to speedTimeLine
502 if (!mySpeedAdaptationStarted) {
503 mySpeedTimeLine[0].second = speed;
504 mySpeedAdaptationStarted = true;
505 }
506 currentTime += DELTA_T; // start slowing down in the step in which this command was issued (the input value of currentTime still reflects the previous step)
507 const double td = MIN2(1.0, STEPS2TIME(currentTime - mySpeedTimeLine[0].first) / MAX2(TS, STEPS2TIME(mySpeedTimeLine[1].first - mySpeedTimeLine[0].first)));
508
509 speed = mySpeedTimeLine[0].second - (mySpeedTimeLine[0].second - mySpeedTimeLine[1].second) * td;
510 if (myConsiderSafeVelocity) {
511 speed = MIN2(speed, vSafe);
512 }
513 if (myConsiderMaxAcceleration) {
514 speed = MIN2(speed, vMax);
515 }
516 if (myConsiderMaxDeceleration) {
517 speed = MAX2(speed, vMin);
518 }
519 }
520 return speed;
521}
522
523double
524MSVehicle::Influencer::gapControlSpeed(SUMOTime currentTime, const SUMOVehicle* veh, double speed, double vSafe, double vMin, double vMax) {
525#ifdef DEBUG_TRACI
526 if DEBUG_COND2(veh) {
527 std::cout << currentTime << " Influencer::gapControlSpeed(): speed=" << speed
528 << ", vSafe=" << vSafe
529 << ", vMin=" << vMin
530 << ", vMax=" << vMax
531 << std::endl;
532 }
533#endif
534 double gapControlSpeed = speed;
535 if (myGapControlState != nullptr && myGapControlState->active) {
536 // Determine leader and the speed that would be chosen by the gap controller
537 const double currentSpeed = veh->getSpeed();
538 const MSVehicle* msVeh = dynamic_cast<const MSVehicle*>(veh);
539 assert(msVeh != nullptr);
540 const double desiredTargetTimeSpacing = myGapControlState->tauTarget * currentSpeed;
541 std::pair<const MSVehicle*, double> leaderInfo;
542 if (myGapControlState->referenceVeh == nullptr) {
543 // No reference vehicle specified -> use current leader as reference
544 const double brakeGap = msVeh->getBrakeGap(true);
545 leaderInfo = msVeh->getLeader(MAX2(desiredTargetTimeSpacing, myGapControlState->addGapCurrent) + MAX2(brakeGap, 20.0));
546#ifdef DEBUG_TRACI
547 if DEBUG_COND2(veh) {
548 std::cout << " --- no refVeh; myGapControlState->addGapCurrent: " << myGapControlState->addGapCurrent << ", brakeGap: " << brakeGap << " in simstep: " << SIMSTEP << std::endl;
549 }
550#endif
551 } else {
552 // Control gap wrt reference vehicle
553 const MSVehicle* leader = myGapControlState->referenceVeh;
554 double dist = msVeh->getDistanceToPosition(leader->getPositionOnLane(), leader->getLane()) - leader->getLength();
555 if (dist > 100000) {
556 // Reference vehicle was not found downstream the ego's route
557 // Maybe, it is behind the ego vehicle
558 dist = - leader->getDistanceToPosition(msVeh->getPositionOnLane(), msVeh->getLane()) - leader->getLength();
559#ifdef DEBUG_TRACI
560 if DEBUG_COND2(veh) {
561 if (dist < -100000) {
562 // also the ego vehicle is not ahead of the reference vehicle -> no CF-relation
563 std::cout << " Ego and reference vehicle are not in CF relation..." << std::endl;
564 } else {
565 std::cout << " Reference vehicle is behind ego..." << std::endl;
566 }
567 }
568#endif
569 }
570 leaderInfo = std::make_pair(leader, dist - msVeh->getVehicleType().getMinGap());
571 }
572 const double fakeDist = MAX2(0.0, leaderInfo.second - myGapControlState->addGapCurrent);
573#ifdef DEBUG_TRACI
574 if DEBUG_COND2(veh) {
575 const double desiredCurrentSpacing = myGapControlState->tauCurrent * currentSpeed;
576 std::cout << " Gap control active:"
577 << " currentSpeed=" << currentSpeed
578 << ", desiredTargetTimeSpacing=" << desiredTargetTimeSpacing
579 << ", desiredCurrentSpacing=" << desiredCurrentSpacing
580 << ", leader=" << (leaderInfo.first == nullptr ? "NULL" : leaderInfo.first->getID())
581 << ", dist=" << leaderInfo.second
582 << ", fakeDist=" << fakeDist
583 << ",\n tauOriginal=" << myGapControlState->tauOriginal
584 << ", tauTarget=" << myGapControlState->tauTarget
585 << ", tauCurrent=" << myGapControlState->tauCurrent
586 << std::endl;
587 }
588#endif
589 if (leaderInfo.first != nullptr) {
590 if (myGapControlState->prevLeader != nullptr && myGapControlState->prevLeader != leaderInfo.first) {
591 // TODO: The leader changed. What to do?
592 }
593 // Remember leader
594 myGapControlState->prevLeader = leaderInfo.first;
595
596 // Calculate desired following speed assuming the alternative headway time
597 MSCFModel* cfm = (MSCFModel*) & (msVeh->getVehicleType().getCarFollowModel());
598 const double origTau = cfm->getHeadwayTime();
599 cfm->setHeadwayTime(myGapControlState->tauCurrent);
600 gapControlSpeed = MIN2(gapControlSpeed,
601 cfm->followSpeed(msVeh, currentSpeed, fakeDist, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first));
602 cfm->setHeadwayTime(origTau);
603#ifdef DEBUG_TRACI
604 if DEBUG_COND2(veh) {
605 std::cout << " -> gapControlSpeed=" << gapControlSpeed;
606 if (myGapControlState->maxDecel > 0) {
607 std::cout << ", with maxDecel bound: " << MAX2(gapControlSpeed, currentSpeed - TS * myGapControlState->maxDecel);
608 }
609 std::cout << std::endl;
610 }
611#endif
612 if (myGapControlState->maxDecel > 0) {
613 gapControlSpeed = MAX2(gapControlSpeed, currentSpeed - TS * myGapControlState->maxDecel);
614 }
615 }
616
617 // Update gap controller
618 // Check (1) if the gap control has established the desired gap,
619 // and (2) if it has maintained active for the given duration afterwards
620 if (myGapControlState->lastUpdate < currentTime) {
621#ifdef DEBUG_TRACI
622 if DEBUG_COND2(veh) {
623 std::cout << " Updating GapControlState." << std::endl;
624 }
625#endif
626 if (myGapControlState->tauCurrent == myGapControlState->tauTarget && myGapControlState->addGapCurrent == myGapControlState->addGapTarget) {
627 if (!myGapControlState->gapAttained) {
628 // Check if the desired gap was established (add the POSITION_EPS to avoid infinite asymptotic behavior without having established the gap)
629 myGapControlState->gapAttained = leaderInfo.first == nullptr || leaderInfo.second > MAX2(desiredTargetTimeSpacing, myGapControlState->addGapTarget) - POSITION_EPS;
630#ifdef DEBUG_TRACI
631 if DEBUG_COND2(veh) {
632 if (myGapControlState->gapAttained) {
633 std::cout << " Target gap was established." << std::endl;
634 }
635 }
636#endif
637 } else {
638 // Count down remaining time if desired gap was established
639 myGapControlState->remainingDuration -= TS;
640#ifdef DEBUG_TRACI
641 if DEBUG_COND2(veh) {
642 std::cout << " Gap control remaining duration: " << myGapControlState->remainingDuration << std::endl;
643 }
644#endif
645 if (myGapControlState->remainingDuration <= 0) {
646#ifdef DEBUG_TRACI
647 if DEBUG_COND2(veh) {
648 std::cout << " Gap control duration expired, deactivating control." << std::endl;
649 }
650#endif
651 // switch off gap control
652 myGapControlState->deactivate();
653 }
654 }
655 } else {
656 // Adjust current headway values
657 myGapControlState->tauCurrent = MIN2(myGapControlState->tauCurrent + myGapControlState->timeHeadwayIncrement, myGapControlState->tauTarget);
658 myGapControlState->addGapCurrent = MIN2(myGapControlState->addGapCurrent + myGapControlState->spaceHeadwayIncrement, myGapControlState->addGapTarget);
659 }
660 }
661 if (myConsiderSafeVelocity) {
662 gapControlSpeed = MIN2(gapControlSpeed, vSafe);
663 }
664 if (myConsiderMaxAcceleration) {
665 gapControlSpeed = MIN2(gapControlSpeed, vMax);
666 }
667 if (myConsiderMaxDeceleration) {
668 gapControlSpeed = MAX2(gapControlSpeed, vMin);
669 }
670 return MIN2(speed, gapControlSpeed);
671 } else {
672 return speed;
673 }
674}
675
676double
678 return myOriginalSpeed;
679}
680
681void
683 myOriginalSpeed = speed;
684}
685
686
687int
688MSVehicle::Influencer::influenceChangeDecision(const SUMOTime currentTime, const MSEdge& currentEdge, const int currentLaneIndex, int state) {
689 // remove leading commands which are no longer valid
690 while (myLaneTimeLine.size() == 1 || (myLaneTimeLine.size() > 1 && currentTime > myLaneTimeLine[1].first)) {
691 myLaneTimeLine.erase(myLaneTimeLine.begin());
692 }
693 ChangeRequest changeRequest = REQUEST_NONE;
694 // do nothing if the time line does not apply for the current time
695 if (myLaneTimeLine.size() >= 2 && currentTime >= myLaneTimeLine[0].first) {
696 const int destinationLaneIndex = myLaneTimeLine[1].second;
697 if (destinationLaneIndex < (int)currentEdge.getLanes().size()) {
698 if (currentLaneIndex > destinationLaneIndex) {
699 changeRequest = REQUEST_RIGHT;
700 } else if (currentLaneIndex < destinationLaneIndex) {
701 changeRequest = REQUEST_LEFT;
702 } else {
703 changeRequest = REQUEST_HOLD;
704 }
705 } else if (currentEdge.getLanes().back()->getOpposite() != nullptr) { // change to opposite direction driving
706 changeRequest = REQUEST_LEFT;
707 state = state | LCA_TRACI;
708 }
709 }
710 // check whether the current reason shall be canceled / overridden
711 if ((state & LCA_WANTS_LANECHANGE_OR_STAY) != 0) {
712 // flags for the current reason
714 if ((state & LCA_TRACI) != 0 && myLatDist != 0) {
715 // security checks
716 if ((myTraciLaneChangePriority == LCP_ALWAYS)
717 || (myTraciLaneChangePriority == LCP_NOOVERLAP && (state & LCA_OVERLAPPING) == 0)) {
718 state &= ~(LCA_BLOCKED | LCA_OVERLAPPING);
719 }
720 // continue sublane change manoeuvre
721 return state;
722 } else if ((state & LCA_STRATEGIC) != 0) {
723 mode = myStrategicLC;
724 } else if ((state & LCA_COOPERATIVE) != 0) {
725 mode = myCooperativeLC;
726 } else if ((state & LCA_SPEEDGAIN) != 0) {
727 mode = mySpeedGainLC;
728 } else if ((state & LCA_KEEPRIGHT) != 0) {
729 mode = myRightDriveLC;
730 } else if ((state & LCA_SUBLANE) != 0) {
731 mode = mySublaneLC;
732 } else if ((state & LCA_TRACI) != 0) {
733 mode = LC_NEVER;
734 } else {
735 WRITE_WARNINGF(TL("Lane change model did not provide a reason for changing (state=%, time=%\n"), toString(state), time2string(currentTime));
736 }
737 if (mode == LC_NEVER) {
738 // cancel all lcModel requests
739 state &= ~LCA_WANTS_LANECHANGE_OR_STAY;
740 state &= ~LCA_URGENT;
741 if (changeRequest == REQUEST_NONE) {
742 // also remove all reasons except TRACI
743 state &= ~LCA_CHANGE_REASONS | LCA_TRACI;
744 }
745 } else if (mode == LC_NOCONFLICT && changeRequest != REQUEST_NONE) {
746 if (
747 ((state & LCA_LEFT) != 0 && changeRequest != REQUEST_LEFT) ||
748 ((state & LCA_RIGHT) != 0 && changeRequest != REQUEST_RIGHT) ||
749 ((state & LCA_STAY) != 0 && changeRequest != REQUEST_HOLD)) {
750 // cancel conflicting lcModel request
751 state &= ~LCA_WANTS_LANECHANGE_OR_STAY;
752 state &= ~LCA_URGENT;
753 }
754 } else if (mode == LC_ALWAYS) {
755 // ignore any TraCI requests
756 return state;
757 }
758 }
759 // apply traci requests
760 if (changeRequest == REQUEST_NONE) {
761 return state;
762 } else {
763 state |= LCA_TRACI;
764 // security checks
765 if ((myTraciLaneChangePriority == LCP_ALWAYS)
766 || (myTraciLaneChangePriority == LCP_NOOVERLAP && (state & LCA_OVERLAPPING) == 0)) {
767 state &= ~(LCA_BLOCKED | LCA_OVERLAPPING);
768 }
769 if (changeRequest != REQUEST_HOLD && myTraciLaneChangePriority != LCP_OPPORTUNISTIC) {
770 state |= LCA_URGENT;
771 }
772 switch (changeRequest) {
773 case REQUEST_HOLD:
774 return state | LCA_STAY;
775 case REQUEST_LEFT:
776 return state | LCA_LEFT;
777 case REQUEST_RIGHT:
778 return state | LCA_RIGHT;
779 default:
780 throw ProcessError(TL("should not happen"));
781 }
782 }
783}
784
785
786double
788 assert(myLaneTimeLine.size() >= 2);
789 assert(currentTime >= myLaneTimeLine[0].first);
790 return STEPS2TIME(myLaneTimeLine[1].first - currentTime);
791}
792
793
794void
796 myConsiderSafeVelocity = ((speedMode & 1) != 0);
797 myConsiderMaxAcceleration = ((speedMode & 2) != 0);
798 myConsiderMaxDeceleration = ((speedMode & 4) != 0);
799 myRespectJunctionPriority = ((speedMode & 8) != 0);
800 myEmergencyBrakeRedLight = ((speedMode & 16) != 0);
801 myRespectJunctionLeaderPriority = ((speedMode & 32) == 0); // inverted!
802 myConsiderSpeedLimit = ((speedMode & 64) == 0); // inverted!
803}
804
805
806void
808 myStrategicLC = (LaneChangeMode)(value & (1 + 2));
809 myCooperativeLC = (LaneChangeMode)((value & (4 + 8)) >> 2);
810 mySpeedGainLC = (LaneChangeMode)((value & (16 + 32)) >> 4);
811 myRightDriveLC = (LaneChangeMode)((value & (64 + 128)) >> 6);
812 myTraciLaneChangePriority = (TraciLaneChangePriority)((value & (256 + 512)) >> 8);
813 mySublaneLC = (LaneChangeMode)((value & (1024 + 2048)) >> 10);
814}
815
816
817void
818MSVehicle::Influencer::setRemoteControlled(Position xyPos, MSLane* l, double pos, double posLat, double angle, int edgeOffset, const ConstMSEdgeVector& route, SUMOTime t) {
819 myRemoteXYPos = xyPos;
820 myRemoteLane = l;
821 myRemotePos = pos;
822 myRemotePosLat = posLat;
823 myRemoteAngle = angle;
824 myRemoteEdgeOffset = edgeOffset;
825 myRemoteRoute = route;
826 myLastRemoteAccess = t;
827}
828
829
830bool
832 return myLastRemoteAccess == MSNet::getInstance()->getCurrentTimeStep();
833}
834
835
836bool
838 return myLastRemoteAccess >= t - TIME2STEPS(10);
839}
840
841
842void
844 if (myRemoteRoute.size() != 0 && myRemoteRoute != v->getRoute().getEdges()) {
845 // only replace route at this time if the vehicle is moving with the flow
846 const bool isForward = v->getLane() != 0 && &v->getLane()->getEdge() == myRemoteRoute[0];
847#ifdef DEBUG_REMOTECONTROL
848 std::cout << SIMSTEP << " updateRemoteControlRoute veh=" << v->getID() << " old=" << toString(v->getRoute().getEdges()) << " new=" << toString(myRemoteRoute) << " fwd=" << isForward << "\n";
849#endif
850 if (isForward) {
851 v->replaceRouteEdges(myRemoteRoute, -1, 0, "traci:moveToXY", true);
852 v->updateBestLanes();
853 }
854 }
855}
856
857
858void
860 const bool wasOnRoad = v->isOnRoad();
861 const bool withinLane = myRemoteLane != nullptr && fabs(myRemotePosLat) < 0.5 * (myRemoteLane->getWidth() + v->getVehicleType().getWidth());
862 const bool keepLane = wasOnRoad && v->getLane() == myRemoteLane;
863 if (v->isOnRoad() && !(keepLane && withinLane)) {
864 if (myRemoteLane != nullptr && &v->getLane()->getEdge() == &myRemoteLane->getEdge()) {
865 // correct odometer which gets incremented via onRemovalFromNet->leaveLane
866 v->myOdometer -= v->getLane()->getLength();
867 }
870 }
871 if (myRemoteRoute.size() != 0 && myRemoteRoute != v->getRoute().getEdges()) {
872 // needed for the insertion step
873#ifdef DEBUG_REMOTECONTROL
874 std::cout << SIMSTEP << " postProcessRemoteControl veh=" << v->getID()
875 << "\n oldLane=" << Named::getIDSecure(v->getLane())
876 << " oldRoute=" << toString(v->getRoute().getEdges())
877 << "\n newLane=" << Named::getIDSecure(myRemoteLane)
878 << " newRoute=" << toString(myRemoteRoute)
879 << " newRouteEdge=" << myRemoteRoute[myRemoteEdgeOffset]->getID()
880 << "\n";
881#endif
882 // clear any prior stops because they cannot apply to the new route
883 const_cast<SUMOVehicleParameter&>(v->getParameter()).stops.clear();
884 v->replaceRouteEdges(myRemoteRoute, -1, 0, "traci:moveToXY", true);
885 myRemoteRoute.clear();
886 }
887 v->myCurrEdge = v->getRoute().begin() + myRemoteEdgeOffset;
888 if (myRemoteLane != nullptr && myRemotePos > myRemoteLane->getLength()) {
889 myRemotePos = myRemoteLane->getLength();
890 }
891 if (myRemoteLane != nullptr && withinLane) {
892 if (keepLane) {
893 // TODO this handles only the case when the new vehicle is completely on the edge
894 const bool needFurtherUpdate = v->myState.myPos < v->getVehicleType().getLength() && myRemotePos >= v->getVehicleType().getLength();
895 v->myState.myPos = myRemotePos;
896 v->myState.myPosLat = myRemotePosLat;
897 if (needFurtherUpdate) {
898 v->myState.myBackPos = v->updateFurtherLanes(v->myFurtherLanes, v->myFurtherLanesPosLat, std::vector<MSLane*>());
899 }
900 } else {
904 if (!v->isOnRoad()) {
905 MSVehicleTransfer::getInstance()->remove(v); // TODO may need optimization, this is linear in the number of vehicles in transfer
906 }
907 myRemoteLane->forceVehicleInsertion(v, myRemotePos, notify, myRemotePosLat);
908 v->updateBestLanes();
909 }
910 if (!wasOnRoad) {
911 v->drawOutsideNetwork(false);
912 }
913 //std::cout << "on road network p=" << myRemoteXYPos << " a=" << myRemoteAngle << " l=" << Named::getIDSecure(myRemoteLane) << " pos=" << myRemotePos << " posLat=" << myRemotePosLat << "\n";
914 myRemoteLane->requireCollisionCheck();
915 } else {
916 if (v->getDeparture() == NOT_YET_DEPARTED) {
917 v->onDepart();
918 }
919 v->drawOutsideNetwork(true);
920 // see updateState
921 double vNext = v->processTraCISpeedControl(
922 v->getMaxSpeed(), v->getSpeed());
923 v->setBrakingSignals(vNext);
925 v->myAcceleration = SPEED2ACCEL(vNext - v->getSpeed());
926 v->myState.mySpeed = vNext;
927 v->updateWaitingTime(vNext);
928 //std::cout << "outside network p=" << myRemoteXYPos << " a=" << myRemoteAngle << " l=" << Named::getIDSecure(myRemoteLane) << "\n";
929 }
930 // ensure that the position is correct (i.e. when the lanePosition is ambiguous at corners)
931 v->setRemoteState(myRemoteXYPos);
932 v->setAngle(GeomHelper::fromNaviDegree(myRemoteAngle));
933}
934
935
936double
938 if (veh->getPosition() == Position::INVALID) {
939 return oldSpeed;
940 }
941 double dist = veh->getPosition().distanceTo2D(myRemoteXYPos);
942 if (myRemoteLane != nullptr) {
943 // if the vehicles is frequently placed on a new edge, the route may
944 // consist only of a single edge. In this case the new edge may not be
945 // on the route so distAlongRoute will be double::max.
946 // In this case we still want a sensible speed value
947 const double distAlongRoute = veh->getDistanceToPosition(myRemotePos, myRemoteLane);
948 if (distAlongRoute != std::numeric_limits<double>::max()) {
949 dist = distAlongRoute;
950 }
951 }
952 //std::cout << SIMTIME << " veh=" << veh->getID() << " oldPos=" << veh->getPosition() << " traciPos=" << myRemoteXYPos << " dist=" << dist << "\n";
953 const double minSpeed = myConsiderMaxDeceleration ?
954 veh->getCarFollowModel().minNextSpeedEmergency(oldSpeed, veh) : 0;
955 const double maxSpeed = (myRemoteLane != nullptr
956 ? myRemoteLane->getVehicleMaxSpeed(veh)
957 : (veh->getLane() != nullptr
958 ? veh->getLane()->getVehicleMaxSpeed(veh)
959 : veh->getMaxSpeed()));
960 return MIN2(maxSpeed, MAX2(minSpeed, DIST2SPEED(dist)));
961}
962
963
964double
966 double dist = 0;
967 if (myRemoteLane == nullptr) {
968 dist = veh->getPosition().distanceTo2D(myRemoteXYPos);
969 } else {
970 // if the vehicles is frequently placed on a new edge, the route may
971 // consist only of a single edge. In this case the new edge may not be
972 // on the route so getDistanceToPosition will return double::max.
973 // In this case we would rather not move the vehicle in executeMove
974 // (updateState) as it would result in emergency braking
975 dist = veh->getDistanceToPosition(myRemotePos, myRemoteLane);
976 }
977 if (dist == std::numeric_limits<double>::max()) {
978 return 0;
979 } else {
980 if (DIST2SPEED(dist) > veh->getMaxSpeed() * 1.1) {
981 WRITE_WARNINGF(TL("Vehicle '%' moved by TraCI from % to % (dist %) with implied speed of % (exceeding maximum speed %). time=%."),
982 veh->getID(), veh->getPosition(), myRemoteXYPos, dist, DIST2SPEED(dist), veh->getMaxSpeed(), time2string(SIMSTEP));
983 // some sanity check here
984 dist = MIN2(dist, SPEED2DIST(veh->getMaxSpeed() * 2));
985 }
986 return dist;
987 }
988}
989
990
991/* -------------------------------------------------------------------------
992 * MSVehicle-methods
993 * ----------------------------------------------------------------------- */
995 MSVehicleType* type, const double speedFactor) :
996 MSBaseVehicle(pars, route, type, speedFactor),
997 myWaitingTime(0),
999 myTimeLoss(0),
1000 myState(0, 0, 0, 0, 0),
1001 myDriverState(nullptr),
1002 myActionStep(true),
1004 myLane(nullptr),
1005 myLaneChangeModel(nullptr),
1006 myLastBestLanesEdge(nullptr),
1008 myAcceleration(0),
1009 myNextTurn(0., nullptr),
1010 mySignals(0),
1011 myAmOnNet(false),
1012 myAmIdling(false),
1014 myAngle(0),
1015 myRawAngle(0),
1017 myStopDist(std::numeric_limits<double>::max()),
1018 myStopSpeed(std::numeric_limits<double>::max()),
1024 myTimeSinceStartup(TIME2STEPS(3600 * 24)),
1025 myHaveStoppedFor(nullptr),
1026 myInfluencer(nullptr) {
1029}
1030
1031
1042
1043
1044void
1046 for (MSLane* further : myFurtherLanes) {
1047 further->resetPartialOccupation(this);
1048 if (further->getBidiLane() != nullptr
1049 && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
1050 further->getBidiLane()->resetPartialOccupation(this);
1051 }
1052 }
1053 if (myLaneChangeModel != nullptr) {
1057 // still needed when calling resetPartialOccupation (getShadowLane) and when removing
1058 // approach information from parallel links
1059 }
1060 myFurtherLanes.clear();
1061 myFurtherLanesPosLat.clear();
1062}
1063
1064
1065void
1067#ifdef DEBUG_ACTIONSTEPS
1068 if (DEBUG_COND) {
1069 std::cout << SIMTIME << " Removing vehicle '" << getID() << "' (reason: " << toString(reason) << ")" << std::endl;
1070 }
1071#endif
1074 leaveLane(reason);
1077 }
1078}
1079
1080
1081void
1088
1089
1090// ------------ interaction with the route
1091bool
1093 // note: not a const method because getDepartLane may call updateBestLanes
1094 if (!(*myCurrEdge)->isTazConnector()) {
1097 if ((*myCurrEdge)->getDepartLane(*this) == nullptr) {
1098 msg = "Invalid departLane definition for vehicle '" + getID() + "'.";
1099 if (myParameter->departLane >= (int)(*myCurrEdge)->getLanes().size()) {
1101 } else {
1103 }
1104 return false;
1105 }
1106 } else {
1107 if ((*myCurrEdge)->allowedLanes(getVClass(), ignoreTransientPermissions()) == nullptr) {
1108 msg = "Vehicle '" + getID() + "' is not allowed to depart on any lane of edge '" + (*myCurrEdge)->getID() + "'.";
1110 return false;
1111 }
1112 }
1114 msg = "Departure speed for vehicle '" + getID() + "' is too high for the vehicle type '" + myType->getID() + "'.";
1116 return false;
1117 }
1118 }
1120 return true;
1121}
1122
1123
1124bool
1126 return hasArrivedInternal(false);
1127}
1128
1129
1130bool
1131MSVehicle::hasArrivedInternal(bool oppositeTransformed) const {
1132 return ((myCurrEdge == myRoute->end() - 1 || (myParameter->arrivalEdge >= 0 && getRoutePosition() >= myParameter->arrivalEdge))
1133 && (myStops.empty() || myStops.front().edge != myCurrEdge || myStops.front().getSpeed() > 0)
1134 && ((myLaneChangeModel->isOpposite() && !oppositeTransformed) ? myLane->getLength() - myState.myPos : myState.myPos) > MIN2(myLane->getLength(), myArrivalPos) - POSITION_EPS
1135 && !isRemoteControlled());
1136}
1137
1138
1139bool
1140MSVehicle::replaceRoute(ConstMSRoutePtr newRoute, const std::string& info, bool onInit, int offset, bool addRouteStops, bool removeStops, std::string* msgReturn) {
1141 if (MSBaseVehicle::replaceRoute(newRoute, info, onInit, offset, addRouteStops, removeStops, msgReturn)) {
1142 // update best lanes (after stops were added)
1143 myLastBestLanesEdge = nullptr;
1145 updateBestLanes(true, onInit ? (*myCurrEdge)->getLanes().front() : 0);
1146 assert(!removeStops || haveValidStopEdges());
1147 if (myStops.size() == 0) {
1148 myStopDist = std::numeric_limits<double>::max();
1149 }
1150 return true;
1151 }
1152 return false;
1153}
1154
1155
1156// ------------ Interaction with move reminders
1157void
1158MSVehicle::workOnMoveReminders(double oldPos, double newPos, double newSpeed) {
1159 // This erasure-idiom works for all stl-sequence-containers
1160 // See Meyers: Effective STL, Item 9
1161 for (MoveReminderCont::iterator rem = myMoveReminders.begin(); rem != myMoveReminders.end();) {
1162 // XXX: calling notifyMove with newSpeed seems not the best choice. For the ballistic update, the average speed is calculated and used
1163 // although a higher order quadrature-formula might be more adequate.
1164 // For the euler case (where the speed is considered constant for each time step) it is conceivable that
1165 // the current calculations may lead to systematic errors for large time steps (compared to reality). Refs. #2579
1166 if (!rem->first->notifyMove(*this, oldPos + rem->second, newPos + rem->second, MAX2(0., newSpeed))) {
1167#ifdef _DEBUG
1168 if (myTraceMoveReminders) {
1169 traceMoveReminder("notifyMove", rem->first, rem->second, false);
1170 }
1171#endif
1172 rem = myMoveReminders.erase(rem);
1173 } else {
1174#ifdef _DEBUG
1175 if (myTraceMoveReminders) {
1176 traceMoveReminder("notifyMove", rem->first, rem->second, true);
1177 }
1178#endif
1179 ++rem;
1180 }
1181 }
1182 if (myEnergyParams != nullptr) {
1183 // TODO make the vehicle energy params a derived class which is a move reminder
1185 }
1186}
1187
1188
1189void
1191 updateWaitingTime(0.); // cf issue 2233
1192
1193 // vehicle move reminders
1194 for (const auto& rem : myMoveReminders) {
1195 rem.first->notifyIdle(*this);
1196 }
1197
1198 // lane move reminders - for aggregated values
1199 for (MSMoveReminder* rem : getLane()->getMoveReminders()) {
1200 rem->notifyIdle(*this);
1201 }
1202}
1203
1204// XXX: consider renaming...
1205void
1207 // save the old work reminders, patching the position information
1208 // add the information about the new offset to the old lane reminders
1209 const double oldLaneLength = myLane->getLength();
1210 for (auto& rem : myMoveReminders) {
1211 rem.second += oldLaneLength;
1212#ifdef _DEBUG
1213// if (rem->first==0) std::cout << "Null reminder (?!)" << std::endl;
1214// std::cout << "Adapted MoveReminder on lane " << ((rem->first->getLane()==0) ? "NULL" : rem->first->getLane()->getID()) <<" position to " << rem->second << std::endl;
1215 if (myTraceMoveReminders) {
1216 traceMoveReminder("adaptedPos", rem.first, rem.second, true);
1217 }
1218#endif
1219 }
1220 for (MSMoveReminder* const rem : enteredLane.getMoveReminders()) {
1221 addReminder(rem);
1222 }
1223}
1224
1225
1226// ------------ Other getter methods
1227double
1229 if (isParking() && getStops().begin()->parkingarea != nullptr) {
1230 return getStops().begin()->parkingarea->getVehicleSlope(*this);
1231 }
1232 if (myLane == nullptr) {
1233 return 0;
1234 }
1236 MSLane* centerLane = myLane;
1237 double centerPos = getPositionOnLane() - getLength() / 2;
1238 int furtherIndex = 0;
1239 while (centerPos < 0 && furtherIndex < (int)myFurtherLanes.size()) {
1240 centerLane = myFurtherLanes[furtherIndex];
1241 centerPos += centerLane->getLength();
1242 furtherIndex++;
1243 }
1244 return centerLane->getShape().slopeDegreeAtOffset(centerLane->interpolateLanePosToGeometryPos(centerPos));
1245 }
1246 const double posLat = myState.myPosLat; // @todo get rid of the '-'
1247 Position p1 = getPosition();
1249 if (p2 == Position::INVALID) {
1250 // Handle special case of vehicle's back reaching out of the network
1251 if (myFurtherLanes.size() > 0) {
1252 p2 = myFurtherLanes.back()->geometryPositionAtOffset(0, -myFurtherLanesPosLat.back());
1253 if (p2 == Position::INVALID) {
1254 // unsuitable lane geometry
1255 p2 = myLane->geometryPositionAtOffset(0, posLat);
1256 }
1257 } else {
1258 p2 = myLane->geometryPositionAtOffset(0, posLat);
1259 }
1260 }
1262}
1263
1264
1266MSVehicle::getPosition(const double offset) const {
1267 if (myLane == nullptr) {
1268 // when called in the context of GUI-Drawing, the simulation step is already incremented
1270 return myCachedPosition;
1271 } else {
1272 return Position::INVALID;
1273 }
1274 }
1275 if (isParking()) {
1276 if (myInfluencer != nullptr && myInfluencer->getLastAccessTimeStep() > getNextStopParameter()->started) {
1277 return myCachedPosition;
1278 }
1279 if (myStops.begin()->parkingarea != nullptr) {
1280 return myStops.begin()->parkingarea->getVehiclePosition(*this);
1281 } else {
1282 // position beside the road
1283 PositionVector shp = myLane->getEdge().getLanes()[0]->getShape();
1286 }
1287 }
1288 const bool changingLanes = myLaneChangeModel->isChangingLanes();
1289 const double posLat = (MSGlobals::gLefthand ? 1 : -1) * getLateralPositionOnLane();
1290 if (offset == 0. && !changingLanes) {
1293 if (MSNet::getInstance()->hasElevation() && MSGlobals::gSublane) {
1295 }
1296 }
1297 return myCachedPosition;
1298 }
1299 Position result = validatePosition(myLane->geometryPositionAtOffset(getPositionOnLane() + offset, posLat), offset);
1300 interpolateLateralZ(result, getPositionOnLane() + offset, posLat);
1301 return result;
1302}
1303
1304
1305void
1306MSVehicle::interpolateLateralZ(Position& pos, double offset, double posLat) const {
1307 const MSLane* shadow = myLaneChangeModel->getShadowLane();
1308 if (shadow != nullptr && pos != Position::INVALID) {
1309 // ignore negative offset
1310 const Position shadowPos = shadow->geometryPositionAtOffset(MAX2(0.0, offset));
1311 if (shadowPos != Position::INVALID && pos.z() != shadowPos.z()) {
1312 const double centerDist = (myLane->getWidth() + shadow->getWidth()) * 0.5;
1313 double relOffset = fabs(posLat) / centerDist;
1314 double newZ = (1 - relOffset) * pos.z() + relOffset * shadowPos.z();
1315 pos.setz(newZ);
1316 }
1317 }
1318}
1319
1320
1321double
1323 double result = getLength() - getPositionOnLane();
1324 if (myLane->isNormal()) {
1325 return MAX2(0.0, result);
1326 }
1327 const MSLane* lane = myLane;
1328 while (lane->isInternal()) {
1329 result += lane->getLength();
1330 lane = lane->getCanonicalSuccessorLane();
1331 }
1332 return result;
1333}
1334
1335
1339 if (!isOnRoad()) {
1340 return Position::INVALID;
1341 }
1342 const std::vector<MSLane*>& bestLanes = getBestLanesContinuation();
1343 auto nextBestLane = bestLanes.begin();
1344 const bool opposite = myLaneChangeModel->isOpposite();
1345 double pos = opposite ? myLane->getLength() - myState.myPos : myState.myPos;
1346 const MSLane* lane = opposite ? myLane->getParallelOpposite() : getLane();
1347 assert(lane != 0);
1348 bool success = true;
1349
1350 while (offset > 0) {
1351 // take into account lengths along internal lanes
1352 while (lane->isInternal() && offset > 0) {
1353 if (offset > lane->getLength() - pos) {
1354 offset -= lane->getLength() - pos;
1355 lane = lane->getLinkCont()[0]->getViaLaneOrLane();
1356 pos = 0.;
1357 if (lane == nullptr) {
1358 success = false;
1359 offset = 0.;
1360 }
1361 } else {
1362 pos += offset;
1363 offset = 0;
1364 }
1365 }
1366 // set nextBestLane to next non-internal lane
1367 while (nextBestLane != bestLanes.end() && *nextBestLane == nullptr) {
1368 ++nextBestLane;
1369 }
1370 if (offset > 0) {
1371 assert(!lane->isInternal());
1372 assert(lane == *nextBestLane);
1373 if (offset > lane->getLength() - pos) {
1374 offset -= lane->getLength() - pos;
1375 ++nextBestLane;
1376 assert(nextBestLane == bestLanes.end() || *nextBestLane != 0);
1377 if (nextBestLane == bestLanes.end()) {
1378 success = false;
1379 offset = 0.;
1380 } else {
1381 const MSLink* link = lane->getLinkTo(*nextBestLane);
1382 assert(link != nullptr);
1383 lane = link->getViaLaneOrLane();
1384 pos = 0.;
1385 }
1386 } else {
1387 pos += offset;
1388 offset = 0;
1389 }
1390 }
1391
1392 }
1393
1394 if (success) {
1396 } else {
1397 return Position::INVALID;
1398 }
1399}
1400
1401
1402double
1404 if (myLane != nullptr) {
1405 return myLane->getVehicleMaxSpeed(this);
1406 }
1407 return myType->getMaxSpeed();
1408}
1409
1410
1412MSVehicle::validatePosition(Position result, double offset) const {
1413 int furtherIndex = 0;
1414 double lastLength = getPositionOnLane();
1415 while (result == Position::INVALID) {
1416 if (furtherIndex >= (int)myFurtherLanes.size()) {
1417 //WRITE_WARNINGF(TL("Could not compute position for vehicle '%', time=%."), getID(), time2string(MSNet::getInstance()->getCurrentTimeStep()));
1418 break;
1419 }
1420 //std::cout << SIMTIME << " veh=" << getID() << " lane=" << myLane->getID() << " pos=" << getPositionOnLane() << " posLat=" << getLateralPositionOnLane() << " offset=" << offset << " result=" << result << " i=" << furtherIndex << " further=" << myFurtherLanes.size() << "\n";
1421 MSLane* further = myFurtherLanes[furtherIndex];
1422 offset += lastLength;
1423 result = further->geometryPositionAtOffset(further->getLength() + offset, -getLateralPositionOnLane());
1424 lastLength = further->getLength();
1425 furtherIndex++;
1426 //std::cout << SIMTIME << " newResult=" << result << "\n";
1427 }
1428 return result;
1429}
1430
1431
1432ConstMSEdgeVector::const_iterator
1434 // too close to the next junction, so avoid an emergency brake here
1435 if (myLane != nullptr && (myCurrEdge + 1) != myRoute->end() && !isRailway(getVClass())) {
1436 if (myLane->isInternal()) {
1437 return myCurrEdge + 1;
1438 }
1439 if (myState.myPos > myLane->getLength() - getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0.)) {
1440 return myCurrEdge + 1;
1441 }
1443 return myCurrEdge + 1;
1444 }
1445 }
1446 return myCurrEdge;
1447}
1448
1449
1450double
1454
1455double
1457 const double angleDiff = getAngleDiff();
1458 return angleDiff == 0
1459 ? std::numeric_limits<double>::max()
1460 : SPEED2DIST(getSpeed()) / fabs(angleDiff);
1461}
1462
1463
1464void
1465MSVehicle::setAngle(double angle, bool straightenFurther) {
1466#ifdef DEBUG_FURTHER
1467 if (DEBUG_COND) {
1468 std::cout << SIMTIME << " veh '" << getID() << " setAngle(" << angle << ") straightenFurther=" << straightenFurther << std::endl;
1469 }
1470#endif
1471 myAngle = angle;
1472 MSLane* next = myLane;
1473 if (straightenFurther && myFurtherLanesPosLat.size() > 0) {
1474 for (int i = 0; i < (int)myFurtherLanes.size(); i++) {
1475 MSLane* further = myFurtherLanes[i];
1476 const MSLink* link = further->getLinkTo(next);
1477 if (link != nullptr) {
1479 next = further;
1480 } else {
1481 break;
1482 }
1483 }
1484 }
1485}
1486
1487
1488void
1489MSVehicle::setActionStepLength(double actionStepLength, bool resetOffset) {
1490 SUMOTime actionStepLengthMillisecs = SUMOVehicleParserHelper::processActionStepLength(actionStepLength);
1491 SUMOTime previousActionStepLength = getActionStepLength();
1492 const bool newActionStepLength = actionStepLengthMillisecs != previousActionStepLength;
1493 if (newActionStepLength) {
1494 getSingularType().setActionStepLength(actionStepLengthMillisecs, resetOffset);
1495 if (!resetOffset) {
1496 updateActionOffset(previousActionStepLength, actionStepLengthMillisecs);
1497 }
1498 }
1499 if (resetOffset) {
1501 }
1502}
1503
1504
1505bool
1507 return myState.mySpeed < (60.0 / 3.6) || myLane->getSpeedLimit() < (60.1 / 3.6);
1508}
1509
1510
1511double
1513 Position p1;
1514 const double posLat = -myState.myPosLat; // @todo get rid of the '-'
1515 const double lefthandSign = (MSGlobals::gLefthand ? -1 : 1);
1516
1517 // if parking manoeuvre is happening then rotate vehicle on each step
1520 }
1521
1522 if (isParking()) {
1523 if (myStops.begin()->parkingarea != nullptr) {
1524 return myStops.begin()->parkingarea->getVehicleAngle(*this);
1525 } else {
1527 }
1528 }
1530 // cannot use getPosition() because it already includes the offset to the side and thus messes up the angle
1531 p1 = myLane->geometryPositionAtOffset(myState.myPos, lefthandSign * posLat);
1532 if (p1 == Position::INVALID && myLane->getShape().length2D() == 0. && myLane->isInternal()) {
1533 // workaround: extrapolate the preceding lane shape
1534 MSLane* predecessorLane = myLane->getCanonicalPredecessorLane();
1535 p1 = predecessorLane->geometryPositionAtOffset(predecessorLane->getLength() + myState.myPos, lefthandSign * posLat);
1536 }
1537 } else {
1538 p1 = getPosition();
1539 }
1540
1541 Position p2;
1542 if (getVehicleType().getParameter().locomotiveLength > 0) {
1543 // articulated vehicle should use the heading of the first part
1544 const double locoLength = MIN2(getVehicleType().getParameter().locomotiveLength, getLength());
1545 p2 = getPosition(-locoLength);
1546 } else {
1547 p2 = getBackPosition();
1548 }
1549 if (p2 == Position::INVALID) {
1550 // Handle special case of vehicle's back reaching out of the network
1551 if (myFurtherLanes.size() > 0) {
1552 p2 = myFurtherLanes.back()->geometryPositionAtOffset(0, -myFurtherLanesPosLat.back());
1553 if (p2 == Position::INVALID) {
1554 // unsuitable lane geometry
1555 p2 = myLane->geometryPositionAtOffset(0, posLat);
1556 }
1557 } else {
1558 p2 = myLane->geometryPositionAtOffset(0, posLat);
1559 }
1560 }
1561 double result = (p1 != p2 ? p2.angleTo2D(p1) :
1563
1564 result += lefthandSign * myLaneChangeModel->calcAngleOffset();
1565
1566#ifdef DEBUG_FURTHER
1567 if (DEBUG_COND) {
1568 std::cout << SIMTIME << " computeAngle veh=" << getID() << " p1=" << p1 << " p2=" << p2 << " angle=" << RAD2DEG(result) << " naviDegree=" << GeomHelper::naviDegree(result) << "\n";
1569 }
1570#endif
1571 return result;
1572}
1573
1574
1575const Position
1577 const double posLat = MSGlobals::gLefthand ? myState.myPosLat : -myState.myPosLat;
1578 Position result;
1579 if (myState.myPos >= myType->getLength()) {
1580 // vehicle is fully on the new lane
1582 } else {
1584 // special case where the target lane has no predecessor
1585#ifdef DEBUG_FURTHER
1586 if (DEBUG_COND) {
1587 std::cout << " getBackPosition veh=" << getID() << " specialCase using myLane=" << myLane->getID() << " pos=0 posLat=" << myState.myPosLat << " result=" << myLane->geometryPositionAtOffset(0, posLat) << "\n";
1588 }
1589#endif
1590 result = myLane->geometryPositionAtOffset(0, posLat);
1591 } else {
1592#ifdef DEBUG_FURTHER
1593 if (DEBUG_COND) {
1594 std::cout << " getBackPosition veh=" << getID() << " myLane=" << myLane->getID() << " further=" << toString(myFurtherLanes) << " myFurtherLanesPosLat=" << toString(myFurtherLanesPosLat) << "\n";
1595 }
1596#endif
1597 if (myFurtherLanes.size() > 0 && !myLaneChangeModel->isChangingLanes()) {
1598 // truncate to 0 if vehicle starts on an edge that is shorter than its length
1599 const double backPos = MAX2(0.0, getBackPositionOnLane(myFurtherLanes.back()));
1600 result = myFurtherLanes.back()->geometryPositionAtOffset(backPos, -myFurtherLanesPosLat.back() * (MSGlobals::gLefthand ? -1 : 1));
1601 } else {
1602 result = myLane->geometryPositionAtOffset(0, posLat);
1603 }
1604 }
1605 }
1607 interpolateLateralZ(result, myState.myPos - myType->getLength(), posLat);
1608 }
1609 return result;
1610}
1611
1612
1613bool
1615 return !isStopped() && !myStops.empty() && myLane != nullptr && &myStops.front().lane->getEdge() == &myLane->getEdge();
1616}
1617
1618bool
1620 return isStopped() && myStops.front().lane == myLane;
1621}
1622
1623bool
1624MSVehicle::keepStopping(bool afterProcessing) const {
1625 if (isStopped()) {
1626 // when coming out of vehicleTransfer we must shift the time forward
1627 return (myStops.front().duration - (afterProcessing ? DELTA_T : 0) > 0 || isStoppedTriggered() || myStops.front().pars.collision
1628 || myStops.front().pars.breakDown || (myStops.front().getSpeed() > 0
1629 && (myState.myPos < MIN2(myStops.front().pars.endPos, myStops.front().lane->getLength() - POSITION_EPS))
1630 && (myStops.front().pars.parking == ParkingType::ONROAD || getSpeed() >= SUMO_const_haltingSpeed)));
1631 } else {
1632 return false;
1633 }
1634}
1635
1636
1639 if (isStopped()) {
1640 return myStops.front().duration;
1641 }
1642 return 0;
1643}
1644
1645
1648 return (myStops.empty() || !myStops.front().pars.collision) ? myCollisionImmunity : MAX2((SUMOTime)0, myStops.front().duration);
1649}
1650
1651
1652bool
1654 return isStopped() && !myStops.empty() && myStops.front().pars.breakDown;
1655}
1656
1657
1658bool
1660 return myCollisionImmunity > 0;
1661}
1662
1663
1664double
1665MSVehicle::processNextStop(double currentVelocity) {
1666 if (myStops.empty()) {
1667 // no stops; pass
1668 return currentVelocity;
1669 }
1670
1671#ifdef DEBUG_STOPS
1672 if (DEBUG_COND) {
1673 std::cout << "\nPROCESS_NEXT_STOP\n" << SIMTIME << " vehicle '" << getID() << "'" << std::endl;
1674 }
1675#endif
1676
1677 MSStop& stop = myStops.front();
1679 if (stop.reached) {
1680 stop.duration -= getActionStepLength();
1681 if (getSpeed() > 0) {
1682 // re-enter stopping places to correct waiting position (except for parkingArea since it's place-based)
1683 if (stop.busstop != nullptr) {
1684 // let the bus stop know the vehicle
1685 stop.busstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
1686 }
1687 if (stop.containerstop != nullptr) {
1688 // let the container stop know the vehicle
1690 }
1691 if (stop.chargingStation != nullptr) {
1692 // let the container stop know the vehicle
1694 }
1695 if (stop.getSpeed() <= 0) {
1696 stop.entryPos = getPositionOnLane();
1697 }
1698 }
1699
1700#ifdef DEBUG_STOPS
1701 if (DEBUG_COND) {
1702 std::cout << SIMTIME << " vehicle '" << getID() << "' reached stop.\n"
1703 << "Remaining duration: " << STEPS2TIME(stop.duration) << std::endl;
1704 if (stop.getSpeed() > 0) {
1705 std::cout << " waypointSpeed=" << stop.getSpeed() << " vehPos=" << myState.myPos << " endPos=" << stop.pars.endPos << "\n";
1706 }
1707 }
1708#endif
1709 if (stop.duration <= 0 && stop.pars.join != "") {
1710 // join this train (part) to another one
1711 MSVehicle* joinVeh = dynamic_cast<MSVehicle*>(MSNet::getInstance()->getVehicleControl().getVehicle(stop.pars.join));
1712 if (joinVeh && joinVeh->hasDeparted() && (joinVeh->joinTrainPart(this) || joinVeh->joinTrainPartFront(this))) {
1713 stop.joinTriggered = false;
1717 }
1718 // avoid collision warning before this vehicle is removed (joinVeh was already made longer)
1720 // mark this vehicle as arrived
1722 const_cast<SUMOVehicleParameter*>(myParameter)->arrivalEdge = getRoutePosition();
1723 // handle transportables that want to continue in the other vehicle
1724 if (myPersonDevice != nullptr) {
1726 }
1727 if (myContainerDevice != nullptr) {
1729 }
1730 }
1731 }
1732 boardTransportables(stop);
1733 if (time > stop.endBoarding) {
1734 // for taxi: cancel customers
1735 MSDevice_Taxi* taxiDevice = static_cast<MSDevice_Taxi*>(getDevice(typeid(MSDevice_Taxi)));
1736 if (taxiDevice != nullptr) {
1737 // may invalidate stops including the current reference
1738 taxiDevice->cancelCurrentCustomers();
1740 return currentVelocity;
1741 }
1742 }
1743 if (!keepStopping() && isOnRoad()) {
1744#ifdef DEBUG_STOPS
1745 if (DEBUG_COND) {
1746 std::cout << SIMTIME << " vehicle '" << getID() << "' resumes from stopping." << std::endl;
1747 }
1748#endif
1750 if (isRail() && hasStops()) {
1751 // stay on the current lane in case of a double stop
1752 const MSStop& nextStop = getNextStop();
1753 if (nextStop.edge == myCurrEdge) {
1754 const double stopSpeed = getCarFollowModel().stopSpeed(this, getSpeed(), nextStop.pars.endPos - myState.myPos);
1755 //std::cout << SIMTIME << " veh=" << getID() << " resumedFromStopping currentVelocity=" << currentVelocity << " stopSpeed=" << stopSpeed << "\n";
1756 return stopSpeed;
1757 }
1758 }
1759 } else {
1760 if (stop.triggered) {
1761 if (getVehicleType().getPersonCapacity() == getPersonNumber()) {
1762 WRITE_WARNINGF(TL("Vehicle '%' ignores triggered stop on lane '%' due to capacity constraints."), getID(), stop.lane->getID());
1763 stop.triggered = false;
1764 } else if (!myAmRegisteredAsWaiting && stop.duration <= DELTA_T) {
1765 // we can only register after waiting for one step. otherwise we might falsely signal a deadlock
1768#ifdef DEBUG_STOPS
1769 if (DEBUG_COND) {
1770 std::cout << SIMTIME << " vehicle '" << getID() << "' registers as waiting for person." << std::endl;
1771 }
1772#endif
1773 }
1774 }
1775 if (stop.containerTriggered) {
1776 if (getVehicleType().getContainerCapacity() == getContainerNumber()) {
1777 WRITE_WARNINGF(TL("Vehicle '%' ignores container triggered stop on lane '%' due to capacity constraints."), getID(), stop.lane->getID());
1778 stop.containerTriggered = false;
1779 } else if (stop.containerTriggered && !myAmRegisteredAsWaiting && stop.duration <= DELTA_T) {
1780 // we can only register after waiting for one step. otherwise we might falsely signal a deadlock
1783#ifdef DEBUG_STOPS
1784 if (DEBUG_COND) {
1785 std::cout << SIMTIME << " vehicle '" << getID() << "' registers as waiting for container." << std::endl;
1786 }
1787#endif
1788 }
1789 }
1790 // joining only takes place after stop duration is over
1792 && stop.duration <= (stop.pars.extension >= 0 ? -stop.pars.extension : 0)) {
1793 if (stop.pars.extension >= 0) {
1794 WRITE_WARNINGF(TL("Vehicle '%' aborts joining after extension of %s at time %."), getID(), STEPS2TIME(stop.pars.extension), time2string(SIMSTEP));
1795 stop.joinTriggered = false;
1796 } else {
1797 // keep stopping indefinitely but ensure that simulation terminates
1800 }
1801 }
1802 if (stop.getSpeed() > 0) {
1803 //waypoint mode
1804 if (stop.duration == 0) {
1805 return stop.getSpeed();
1806 } else {
1807 // stop for 'until' (computed in planMove)
1808 return currentVelocity;
1809 }
1810 } else {
1811 // brake
1813 return 0;
1814 } else {
1815 // ballistic:
1816 return getSpeed() - getCarFollowModel().getMaxDecel();
1817 }
1818 }
1819 }
1820 } else {
1821
1822#ifdef DEBUG_STOPS
1823 if (DEBUG_COND) {
1824 std::cout << SIMTIME << " vehicle '" << getID() << "' hasn't reached next stop." << std::endl;
1825 }
1826#endif
1827 //std::cout << SIMTIME << " myStopDist=" << myStopDist << " bGap=" << getBrakeGap(myLane->getVehicleMaxSpeed(this)) << "\n";
1828 if (stop.pars.onDemand && !stop.skipOnDemand && myStopDist <= getCarFollowModel().brakeGap(myLane->getVehicleMaxSpeed(this))) {
1829 MSNet* const net = MSNet::getInstance();
1830 const bool noExits = ((myPersonDevice == nullptr || !myPersonDevice->anyLeavingAtStop(stop))
1831 && (myContainerDevice == nullptr || !myContainerDevice->anyLeavingAtStop(stop)));
1832 const bool noEntries = ((!net->hasPersons() || !net->getPersonControl().hasAnyWaiting(stop.getEdge(), this))
1833 && (!net->hasContainers() || !net->getContainerControl().hasAnyWaiting(stop.getEdge(), this)));
1834 if (noExits && noEntries) {
1835 //std::cout << " skipOnDemand\n";
1836 stop.skipOnDemand = true;
1837 // bestLanes must be extended past this stop
1838 updateBestLanes(true);
1839 }
1840 }
1841 // is the next stop on the current lane?
1842 if (stop.edge == myCurrEdge) {
1843 // get the stopping position
1844 bool useStoppingPlace = stop.busstop != nullptr || stop.containerstop != nullptr || stop.parkingarea != nullptr;
1845 bool fitsOnStoppingPlace = true;
1846 if (!stop.skipOnDemand) { // no need to check available space if we skip it anyway
1847 if (stop.busstop != nullptr) {
1848 fitsOnStoppingPlace &= stop.busstop->fits(myState.myPos, *this);
1849 }
1850 if (stop.containerstop != nullptr) {
1851 fitsOnStoppingPlace &= stop.containerstop->fits(myState.myPos, *this);
1852 }
1853 // if the stop is a parking area we check if there is a free position on the area
1854 if (stop.parkingarea != nullptr) {
1855 fitsOnStoppingPlace &= myState.myPos > stop.parkingarea->getBeginLanePosition();
1856 if (stop.parkingarea->getOccupancy() >= stop.parkingarea->getCapacity()) {
1857 fitsOnStoppingPlace = false;
1858 // trigger potential parkingZoneReroute
1859 MSParkingArea* oldParkingArea = stop.parkingarea;
1860 for (MSMoveReminder* rem : myLane->getMoveReminders()) {
1861 if (rem->isParkingRerouter()) {
1862 rem->notifyEnter(*this, MSMoveReminder::NOTIFICATION_PARKING_REROUTE, myLane);
1863 }
1864 }
1865 if (myStops.empty() || myStops.front().parkingarea != oldParkingArea) {
1866 // rerouted, keep driving
1867 return currentVelocity;
1868 }
1869 } else if (stop.parkingarea->getOccupancyIncludingReservations(this) >= stop.parkingarea->getCapacity()) {
1870 fitsOnStoppingPlace = false;
1871 } else if (stop.parkingarea->parkOnRoad() && stop.parkingarea->getLotIndex(this) < 0) {
1872 fitsOnStoppingPlace = false;
1873 }
1874 }
1875 }
1876 const double targetPos = myState.myPos + myStopDist + (stop.getSpeed() > 0 ? (stop.pars.startPos - stop.pars.endPos) : 0);
1877 double reachedThreshold = (useStoppingPlace ? targetPos - STOPPING_PLACE_OFFSET : stop.getReachedThreshold()) - NUMERICAL_EPS;
1878 if (stop.busstop != nullptr && stop.getSpeed() <= 0 && getWaitingTime() > DELTA_T && myLane == stop.lane) {
1879 // count (long) busStop as reached when fully within and jammed before the designated spot
1880 reachedThreshold = MIN2(reachedThreshold, stop.pars.startPos + getLength());
1881 }
1882 const bool posReached = myState.pos() >= reachedThreshold && currentVelocity <= stop.getSpeed() + SUMO_const_haltingSpeed && myLane == stop.lane;
1883#ifdef DEBUG_STOPS
1884 if (DEBUG_COND) {
1885 std::cout << " pos=" << myState.pos() << " speed=" << currentVelocity << " targetPos=" << targetPos << " fits=" << fitsOnStoppingPlace
1886 << " reachedThresh=" << reachedThreshold
1887 << " posReached=" << posReached
1888 << " myLane=" << Named::getIDSecure(myLane)
1889 << " stopLane=" << Named::getIDSecure(stop.lane)
1890 << "\n";
1891 }
1892#endif
1893 if (posReached && !fitsOnStoppingPlace && MSStopOut::active()) {
1894 MSStopOut::getInstance()->stopBlocked(this, time);
1895 }
1896 if (fitsOnStoppingPlace && posReached && (!MSGlobals::gModelParkingManoeuver || myManoeuvre.entryManoeuvreIsComplete(this))) {
1897 // ok, we may stop (have reached the stop) and either we are not modelling maneuvering or have completed entry
1898 stop.reached = true;
1899 if (!stop.startedFromState) {
1900 stop.pars.started = time;
1901 }
1902#ifdef DEBUG_STOPS
1903 if (DEBUG_COND) {
1904 std::cout << SIMTIME << " vehicle '" << getID() << "' reached next stop." << std::endl;
1905 }
1906#endif
1907 if (MSStopOut::active()) {
1909 }
1910 myLane->getEdge().addWaiting(this);
1913 // compute stopping time
1914 stop.duration = stop.getMinDuration(time);
1915 stop.endBoarding = stop.pars.extension >= 0 ? time + stop.duration + stop.pars.extension : SUMOTime_MAX;
1916 MSDevice_Taxi* taxiDevice = static_cast<MSDevice_Taxi*>(getDevice(typeid(MSDevice_Taxi)));
1917 if (taxiDevice != nullptr && stop.pars.extension >= 0) {
1918 // earliestPickupTime is set with waitUntil
1919 stop.endBoarding = MAX2(time, stop.pars.waitUntil) + stop.pars.extension;
1920 }
1921 if (stop.getSpeed() > 0) {
1922 // ignore duration parameter in waypoint mode unless 'until' or 'ended' are set
1923 if (stop.getUntil() > time) {
1924 stop.duration = stop.getUntil() - time;
1925 } else {
1926 stop.duration = 0;
1927 }
1928 } else {
1929 stop.entryPos = getPositionOnLane();
1930 }
1931 if (stop.busstop != nullptr) {
1932 // let the bus stop know the vehicle
1933 stop.busstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
1934 }
1935 if (stop.containerstop != nullptr) {
1936 // let the container stop know the vehicle
1938 }
1939 if (stop.parkingarea != nullptr && stop.getSpeed() <= 0) {
1940 // let the parking area know the vehicle
1941 stop.parkingarea->enter(this, stop.pars.parking == ParkingType::OFFROAD);
1942 }
1943 if (stop.chargingStation != nullptr) {
1944 // let the container stop know the vehicle
1946 }
1947
1948 if (stop.pars.tripId != "") {
1949 ((SUMOVehicleParameter&)getParameter()).setParameter("tripId", stop.pars.tripId);
1950 }
1951 if (stop.pars.line != "") {
1952 ((SUMOVehicleParameter&)getParameter()).line = stop.pars.line;
1953 }
1954 if (stop.pars.split != "") {
1955 // split the train
1956 MSVehicle* splitVeh = dynamic_cast<MSVehicle*>(MSNet::getInstance()->getVehicleControl().getVehicle(stop.pars.split));
1957 if (splitVeh == nullptr) {
1958 WRITE_WARNINGF(TL("Vehicle '%' to split from vehicle '%' is not known. time=%."), stop.pars.split, getID(), SIMTIME)
1959 } else {
1961 splitVeh->getRoute().getEdges()[0]->removeWaiting(splitVeh);
1963 const double newLength = MAX2(myType->getLength() - splitVeh->getVehicleType().getLength(),
1965 getSingularType().setLength(newLength);
1966 // handle transportables that want to continue in the split part
1967 if (myPersonDevice != nullptr) {
1969 }
1970 if (myContainerDevice != nullptr) {
1972 }
1974 const double backShift = splitVeh->getLength() + getVehicleType().getMinGap();
1975 myState.myPos -= backShift;
1976 myState.myBackPos -= backShift;
1977 }
1978 }
1979 }
1980
1981 boardTransportables(stop);
1982 if (stop.pars.posLat != INVALID_DOUBLE) {
1983 myState.myPosLat = stop.pars.posLat;
1984 }
1985 }
1986 }
1987 }
1988 return currentVelocity;
1989}
1990
1991
1992void
1994 if (stop.skipOnDemand) {
1995 return;
1996 }
1997 // we have reached the stop
1998 // any waiting persons may board now
2000 MSNet* const net = MSNet::getInstance();
2001 const bool boarded = (time <= stop.endBoarding
2002 && net->hasPersons()
2004 && stop.numExpectedPerson == 0);
2005 // load containers
2006 const bool loaded = (time <= stop.endBoarding
2007 && net->hasContainers()
2009 && stop.numExpectedContainer == 0);
2010
2011 bool unregister = false;
2012 if (time > stop.endBoarding) {
2013 stop.triggered = false;
2014 stop.containerTriggered = false;
2016 unregister = true;
2018 }
2019 }
2020 if (boarded) {
2021 // the triggering condition has been fulfilled. Maybe we want to wait a bit longer for additional riders (car pooling)
2023 unregister = true;
2024 }
2025 stop.triggered = false;
2027 }
2028 if (loaded) {
2029 // the triggering condition has been fulfilled
2031 unregister = true;
2032 }
2033 stop.containerTriggered = false;
2035 }
2036
2037 if (unregister) {
2039#ifdef DEBUG_STOPS
2040 if (DEBUG_COND) {
2041 std::cout << SIMTIME << " vehicle '" << getID() << "' unregisters as waiting for transportable." << std::endl;
2042 }
2043#endif
2044 }
2045}
2046
2047bool
2049 // check if veh is close enough to be joined to the rear of this vehicle
2050 MSLane* backLane = myFurtherLanes.size() == 0 ? myLane : myFurtherLanes.back();
2051 double gap = getBackPositionOnLane() - veh->getPositionOnLane();
2052 if (isStopped() && myStops.begin()->duration <= DELTA_T && myStops.begin()->joinTriggered && backLane == veh->getLane()
2053 && gap >= 0 && gap <= getVehicleType().getMinGap() + 1) {
2054 const double newLength = myType->getLength() + veh->getVehicleType().getLength();
2055 getSingularType().setLength(newLength);
2056 myStops.begin()->joinTriggered = false;
2060 }
2061 return true;
2062 } else {
2063 return false;
2064 }
2065}
2066
2067
2068bool
2070 // check if veh is close enough to be joined to the front of this vehicle
2071 MSLane* backLane = veh->myFurtherLanes.size() == 0 ? veh->myLane : veh->myFurtherLanes.back();
2072 double gap = veh->getBackPositionOnLane(backLane) - getPositionOnLane();
2073 if (isStopped() && myStops.begin()->duration <= DELTA_T && myStops.begin()->joinTriggered && backLane == getLane()
2074 && gap >= 0 && gap <= getVehicleType().getMinGap() + 1) {
2075 double skippedLaneLengths = 0;
2076 if (veh->myFurtherLanes.size() > 0) {
2077 skippedLaneLengths += getLane()->getLength();
2078 // this vehicle must be moved to the lane of veh
2079 // ensure that lane and furtherLanes of veh match our route
2080 int routeIndex = getRoutePosition();
2081 if (myLane->isInternal()) {
2082 routeIndex++;
2083 }
2084 for (int i = (int)veh->myFurtherLanes.size() - 1; i >= 0; i--) {
2085 MSEdge* edge = &veh->myFurtherLanes[i]->getEdge();
2086 if (edge->isInternal()) {
2087 continue;
2088 }
2089 if (!edge->isInternal() && edge != myRoute->getEdges()[routeIndex]) {
2090 std::string warn = TL("Cannot join vehicle '%' to vehicle '%' due to incompatible routes. time=%.");
2091 WRITE_WARNINGF(warn, veh->getID(), getID(), time2string(SIMSTEP));
2092 return false;
2093 }
2094 routeIndex++;
2095 }
2096 if (veh->getCurrentEdge()->getNormalSuccessor() != myRoute->getEdges()[routeIndex]) {
2097 std::string warn = TL("Cannot join vehicle '%' to vehicle '%' due to incompatible routes. time=%.");
2098 WRITE_WARNINGF(warn, veh->getID(), getID(), time2string(SIMSTEP));
2099 return false;
2100 }
2101 for (int i = (int)veh->myFurtherLanes.size() - 2; i >= 0; i--) {
2102 skippedLaneLengths += veh->myFurtherLanes[i]->getLength();
2103 }
2104 }
2105
2106 const double newLength = myType->getLength() + veh->getVehicleType().getLength();
2107 getSingularType().setLength(newLength);
2108 // lane will be advanced just as for regular movement
2109 myState.myPos = skippedLaneLengths + veh->getPositionOnLane();
2110 myStops.begin()->joinTriggered = false;
2114 }
2115 return true;
2116 } else {
2117 return false;
2118 }
2119}
2120
2121double
2122MSVehicle::getBrakeGap(bool delayed) const {
2123 return getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), delayed ? getCarFollowModel().getHeadwayTime() : 0);
2124}
2125
2126
2127bool
2130 if (myActionStep) {
2131 myLastActionTime = t;
2132 }
2133 return myActionStep;
2134}
2135
2136
2137void
2138MSVehicle::resetActionOffset(const SUMOTime timeUntilNextAction) {
2139 myLastActionTime = MSNet::getInstance()->getCurrentTimeStep() + timeUntilNextAction;
2140}
2141
2142
2143void
2144MSVehicle::updateActionOffset(const SUMOTime oldActionStepLength, const SUMOTime newActionStepLength) {
2146 SUMOTime timeSinceLastAction = now - myLastActionTime;
2147 if (timeSinceLastAction == 0) {
2148 // Action was scheduled now, may be delayed be new action step length
2149 timeSinceLastAction = oldActionStepLength;
2150 }
2151 if (timeSinceLastAction >= newActionStepLength) {
2152 // Action point required in this step
2153 myLastActionTime = now;
2154 } else {
2155 SUMOTime timeUntilNextAction = newActionStepLength - timeSinceLastAction;
2156 resetActionOffset(timeUntilNextAction);
2157 }
2158}
2159
2160
2161
2162void
2163MSVehicle::planMove(const SUMOTime t, const MSLeaderInfo& ahead, const double lengthsInFront) {
2164#ifdef DEBUG_PLAN_MOVE
2165 if (DEBUG_COND) {
2166 std::cout
2167 << "\nPLAN_MOVE\n"
2168 << SIMTIME
2169 << std::setprecision(gPrecision)
2170 << " veh=" << getID()
2171 << " lane=" << myLane->getID()
2172 << " pos=" << getPositionOnLane()
2173 << " posLat=" << getLateralPositionOnLane()
2174 << " speed=" << getSpeed()
2175 << "\n";
2176 }
2177#endif
2178 // Update the driver state
2179 if (hasDriverState()) {
2181 setActionStepLength(myDriverState->getDriverState()->getActionStepLength(), false);
2182 }
2183
2185 if (!checkActionStep(t)) {
2186#ifdef DEBUG_ACTIONSTEPS
2187 if (DEBUG_COND) {
2188 std::cout << STEPS2TIME(t) << " vehicle '" << getID() << "' skips action." << std::endl;
2189 }
2190#endif
2191 // During non-action passed drive items still need to be removed
2192 // @todo rather work with updating myCurrentDriveItem (refs #3714)
2194 return;
2195 } else {
2196#ifdef DEBUG_ACTIONSTEPS
2197 if (DEBUG_COND) {
2198 std::cout << STEPS2TIME(t) << " vehicle = '" << getID() << "' takes action." << std::endl;
2199 }
2200#endif
2202 if (myInfluencer != nullptr) {
2204 }
2206#ifdef DEBUG_PLAN_MOVE
2207 if (DEBUG_COND) {
2208 DriveItemVector::iterator i;
2209 for (i = myLFLinkLanes.begin(); i != myLFLinkLanes.end(); ++i) {
2210 std::cout
2211 << " vPass=" << (*i).myVLinkPass
2212 << " vWait=" << (*i).myVLinkWait
2213 << " linkLane=" << ((*i).myLink == 0 ? "NULL" : (*i).myLink->getViaLaneOrLane()->getID())
2214 << " request=" << (*i).mySetRequest
2215 << "\n";
2216 }
2217 }
2218#endif
2219 checkRewindLinkLanes(lengthsInFront, myLFLinkLanes);
2221 // ideally would only do this with the call inside planMoveInternal - but that needs a const method
2222 // so this is a kludge here - nuisance as it adds an extra check in a busy loop
2226 }
2227 }
2228 }
2230}
2231
2232
2233bool
2234MSVehicle::brakeForOverlap(const MSLink* link, const MSLane* lane) const {
2235 // @review needed
2236 //const double futurePosLat = getLateralPositionOnLane() + link->getLateralShift();
2237 //const double overlap = getLateralOverlap(futurePosLat, link->getViaLaneOrLane());
2238 //const double edgeWidth = link->getViaLaneOrLane()->getEdge().getWidth();
2239 const double futurePosLat = getLateralPositionOnLane() + (
2240 lane != myLane && lane->isInternal() ? lane->getIncomingLanes()[0].viaLink->getLateralShift() : 0);
2241 const double overlap = getLateralOverlap(futurePosLat, lane);
2242 const double edgeWidth = lane->getEdge().getWidth();
2243 const bool result = (overlap > POSITION_EPS
2244 // do not get stuck on narrow edges
2245 && getVehicleType().getWidth() <= edgeWidth
2246 && link->getViaLane() == nullptr
2247 // this is the exit link of a junction. The normal edge should support the shadow
2248 && ((myLaneChangeModel->getShadowLane(link->getLane()) == nullptr)
2249 // the shadow lane must be permitted
2250 || !myLaneChangeModel->getShadowLane(link->getLane())->allowsVehicleClass(getVClass())
2251 // the internal lane after an internal junction has no parallel lane. make sure there is no shadow before continuing
2252 || (lane->getEdge().isInternal() && lane->getIncomingLanes()[0].lane->getEdge().isInternal()))
2253 // ignore situations where the shadow lane is part of a double-connection with the current lane
2254 && (myLaneChangeModel->getShadowLane() == nullptr
2255 || myLaneChangeModel->getShadowLane()->getLinkCont().size() == 0
2256 || myLaneChangeModel->getShadowLane()->getLinkCont().front()->getLane() != link->getLane())
2257 // emergency vehicles may do some crazy stuff
2259
2260#ifdef DEBUG_PLAN_MOVE
2261 if (DEBUG_COND) {
2262 std::cout << SIMTIME << " veh=" << getID() << " link=" << link->getDescription() << " lane=" << lane->getID()
2263 << " linkLane=" << link->getLane()->getID()
2264 << " shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane())
2265 << " shift=" << link->getLateralShift()
2266 << " fpLat=" << futurePosLat << " overlap=" << overlap << " w=" << getVehicleType().getWidth()
2267 << " shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane(link->getLane()))
2268 << " result=" << result << "\n";
2269 }
2270#endif
2271 return result;
2272}
2273
2274
2275
2276void
2277MSVehicle::planMoveInternal(const SUMOTime t, MSLeaderInfo ahead, DriveItemVector& lfLinks, double& newStopDist, double& newStopSpeed, std::pair<double, const MSLink*>& nextTurn) const {
2278 lfLinks.clear();
2279 newStopDist = std::numeric_limits<double>::max();
2280 //
2281 const MSCFModel& cfModel = getCarFollowModel();
2282 const double vehicleLength = getVehicleType().getLength();
2283 const double maxV = cfModel.maxNextSpeed(myState.mySpeed, this);
2284 const double maxVD = MAX2(getMaxSpeed(), MIN2(maxV, getDesiredMaxSpeed()));
2285 const bool opposite = myLaneChangeModel->isOpposite();
2286 // maxVD is possibly higher than vType-maxSpeed and in this case laneMaxV may be higher as well
2287 double laneMaxV = myLane->getVehicleMaxSpeed(this, maxVD);
2288 const double vMinComfortable = cfModel.minNextSpeed(getSpeed(), this);
2289 double lateralShift = 0;
2290 if (isRail()) {
2291 // speed limits must hold for the whole length of the train
2292 for (MSLane* l : myFurtherLanes) {
2293 laneMaxV = MIN2(laneMaxV, l->getVehicleMaxSpeed(this, maxVD));
2294#ifdef DEBUG_PLAN_MOVE
2295 if (DEBUG_COND) {
2296 std::cout << " laneMaxV=" << laneMaxV << " lane=" << l->getID() << "\n";
2297 }
2298#endif
2299 }
2300 }
2301 // speed limits are not emergencies (e.g. when the limit changes suddenly due to TraCI or a variableSpeedSignal)
2302 laneMaxV = MAX2(laneMaxV, vMinComfortable);
2304 laneMaxV = std::numeric_limits<double>::max();
2305 }
2306 // v is the initial maximum velocity of this vehicle in this step
2307 double v = cfModel.maximumLaneSpeedCF(this, maxV, laneMaxV);
2308 // if we are modelling parking then we dawdle until the manoeuvre is complete - by setting a very low max speed
2309 // in practice this only applies to exit manoeuvre because entry manoeuvre just delays setting stop.reached - when the vehicle is virtually stopped
2312 }
2313
2314 if (myInfluencer != nullptr) {
2315 const double vMin = MAX2(0., cfModel.minNextSpeed(myState.mySpeed, this));
2316#ifdef DEBUG_TRACI
2317 if (DEBUG_COND) {
2318 std::cout << SIMTIME << " veh=" << getID() << " speedBeforeTraci=" << v;
2319 }
2320#endif
2321 v = myInfluencer->influenceSpeed(t, v, v, vMin, maxV);
2322#ifdef DEBUG_TRACI
2323 if (DEBUG_COND) {
2324 std::cout << " influencedSpeed=" << v;
2325 }
2326#endif
2327 v = myInfluencer->gapControlSpeed(t, this, v, v, vMin, maxV);
2328#ifdef DEBUG_TRACI
2329 if (DEBUG_COND) {
2330 std::cout << " gapControlSpeed=" << v << "\n";
2331 }
2332#endif
2333 }
2334 // all links within dist are taken into account (potentially)
2335 const double dist = SPEED2DIST(maxV) + cfModel.brakeGap(maxV);
2336
2337 const std::vector<MSLane*>& bestLaneConts = getBestLanesContinuation();
2338#ifdef DEBUG_PLAN_MOVE
2339 if (DEBUG_COND) {
2340 std::cout << " dist=" << dist << " bestLaneConts=" << toString(bestLaneConts)
2341 << "\n maxV=" << maxV << " laneMaxV=" << laneMaxV << " v=" << v << "\n";
2342 }
2343#endif
2344 assert(bestLaneConts.size() > 0);
2345 bool hadNonInternal = false;
2346 // the distance already "seen"; in the following always up to the end of the current "lane"
2347 double seen = opposite ? myState.myPos : myLane->getLength() - myState.myPos;
2348 nextTurn.first = seen;
2349 nextTurn.second = nullptr;
2350 bool encounteredTurn = (MSGlobals::gLateralResolution <= 0); // next turn is only needed for sublane
2351 double seenNonInternal = 0;
2352 double seenInternal = myLane->isInternal() ? seen : 0;
2353 double vLinkPass = MIN2(cfModel.estimateSpeedAfterDistance(seen, v, cfModel.getMaxAccel()), laneMaxV); // upper bound
2354 int view = 0;
2355 DriveProcessItem* lastLink = nullptr;
2356 bool slowedDownForMinor = false; // whether the vehicle already had to slow down on approach to a minor link
2357 double mustSeeBeforeReversal = 0;
2358 // iterator over subsequent lanes and fill lfLinks until stopping distance or stopped
2359 const MSLane* lane = opposite ? myLane->getParallelOpposite() : myLane;
2360 assert(lane != 0);
2361 const MSLane* leaderLane = myLane;
2362 bool foundRailSignal = !isRail();
2363 bool planningToStop = false;
2364#ifdef PARALLEL_STOPWATCH
2365 myLane->getStopWatch()[0].start();
2366#endif
2367
2368 // optionally slow down to match arrival time
2369 const double sfp = getVehicleType().getParameter().speedFactorPremature;
2370 if (v > vMinComfortable && hasStops() && myStops.front().pars.arrival >= 0 && sfp > 0
2371 && v > myLane->getSpeedLimit() * sfp
2372 && !myStops.front().reached) {
2373 const double vSlowDown = slowDownForSchedule(vMinComfortable);
2374 v = MIN2(v, vSlowDown);
2375 }
2376 auto stopIt = myStops.begin();
2377 while (true) {
2378 // check leader on lane
2379 // leader is given for the first edge only
2380 if (opposite &&
2381 (leaderLane->getVehicleNumberWithPartials() > 1
2382 || (leaderLane != myLane && leaderLane->getVehicleNumber() > 0))) {
2383 ahead.clear();
2384 // find opposite-driving leader that must be respected on the currently looked at lane
2385 // (only looking at one lane at a time)
2386 const double backOffset = leaderLane == myLane ? getPositionOnLane() : leaderLane->getLength();
2387 const double gapOffset = leaderLane == myLane ? 0 : seen - leaderLane->getLength();
2388 const MSLeaderDistanceInfo cands = leaderLane->getFollowersOnConsecutive(this, backOffset, true, backOffset, MSLane::MinorLinkMode::FOLLOW_NEVER);
2389 MSLeaderDistanceInfo oppositeLeaders(leaderLane->getWidth(), this, 0.);
2390 const double minTimeToLeaveLane = MSGlobals::gSublane ? MAX2(TS, (0.5 * myLane->getWidth() - getLateralPositionOnLane()) / getVehicleType().getMaxSpeedLat()) : TS;
2391 for (int i = 0; i < cands.numSublanes(); i++) {
2392 CLeaderDist cand = cands[i];
2393 if (cand.first != 0) {
2394 if ((cand.first->myLaneChangeModel->isOpposite() && cand.first->getLaneChangeModel().getShadowLane() != leaderLane)
2395 || (!cand.first->myLaneChangeModel->isOpposite() && cand.first->getLaneChangeModel().getShadowLane() == leaderLane)) {
2396 // respect leaders that also drive in the opposite direction (fully or with some overlap)
2397 oppositeLeaders.addLeader(cand.first, cand.second + gapOffset - getVehicleType().getMinGap() + cand.first->getVehicleType().getMinGap() - cand.first->getVehicleType().getLength());
2398 } else {
2399 // avoid frontal collision
2400 const bool assumeStopped = cand.first->isStopped() || cand.first->getWaitingSeconds() > 1;
2401 const double predMaxDist = cand.first->getSpeed() + (assumeStopped ? 0 : cand.first->getCarFollowModel().getMaxAccel()) * minTimeToLeaveLane;
2402 if (cand.second >= 0 && (cand.second - v * minTimeToLeaveLane - predMaxDist < 0 || assumeStopped)) {
2403 oppositeLeaders.addLeader(cand.first, cand.second + gapOffset - predMaxDist - getVehicleType().getMinGap());
2404 }
2405 }
2406 }
2407 }
2408#ifdef DEBUG_PLAN_MOVE
2409 if (DEBUG_COND) {
2410 std::cout << " leaderLane=" << leaderLane->getID() << " gapOffset=" << gapOffset << " minTimeToLeaveLane=" << minTimeToLeaveLane
2411 << " cands=" << cands.toString() << " oppositeLeaders=" << oppositeLeaders.toString() << "\n";
2412 }
2413#endif
2414 adaptToLeaderDistance(oppositeLeaders, 0, seen, lastLink, v, vLinkPass);
2415 } else {
2417 const double rightOL = getRightSideOnLane(lane) + lateralShift;
2418 const double leftOL = getLeftSideOnLane(lane) + lateralShift;
2419 const bool outsideLeft = leftOL > lane->getWidth();
2420#ifdef DEBUG_PLAN_MOVE
2421 if (DEBUG_COND) {
2422 std::cout << SIMTIME << " veh=" << getID() << " lane=" << lane->getID() << " rightOL=" << rightOL << " leftOL=" << leftOL << "\n";
2423 }
2424#endif
2425 if (rightOL < 0 || outsideLeft) {
2426 MSLeaderInfo outsideLeaders(lane->getWidth());
2427 // if ego is driving outside lane bounds we must consider
2428 // potential leaders that are also outside bounds
2429 int sublaneOffset = 0;
2430 if (outsideLeft) {
2431 sublaneOffset = MIN2(-1, -(int)ceil((leftOL - lane->getWidth()) / MSGlobals::gLateralResolution));
2432 } else {
2433 sublaneOffset = MAX2(1, (int)ceil(-rightOL / MSGlobals::gLateralResolution));
2434 }
2435 outsideLeaders.setSublaneOffset(sublaneOffset);
2436#ifdef DEBUG_PLAN_MOVE
2437 if (DEBUG_COND) {
2438 std::cout << SIMTIME << " veh=" << getID() << " lane=" << lane->getID() << " sublaneOffset=" << sublaneOffset << " outsideLeft=" << outsideLeft << "\n";
2439 }
2440#endif
2441 for (const MSVehicle* cand : lane->getVehiclesSecure()) {
2442 if ((lane != myLane || cand->getPositionOnLane() > getPositionOnLane())
2443 && ((!outsideLeft && cand->getLeftSideOnEdge() < 0)
2444 || (outsideLeft && cand->getLeftSideOnEdge() > lane->getEdge().getWidth()))) {
2445 outsideLeaders.addLeader(cand, true);
2446#ifdef DEBUG_PLAN_MOVE
2447 if (DEBUG_COND) {
2448 std::cout << " outsideLeader=" << cand->getID() << " ahead=" << outsideLeaders.toString() << "\n";
2449 }
2450#endif
2451 }
2452 }
2453 lane->releaseVehicles();
2454 if (outsideLeaders.hasVehicles()) {
2455 adaptToLeaders(outsideLeaders, lateralShift, seen, lastLink, leaderLane, v, vLinkPass);
2456 }
2457 }
2458 }
2459 adaptToLeaders(ahead, lateralShift, seen, lastLink, leaderLane, v, vLinkPass);
2460 }
2461 if (lastLink != nullptr) {
2462 lastLink->myVLinkWait = MIN2(lastLink->myVLinkWait, v);
2463 }
2464#ifdef DEBUG_PLAN_MOVE
2465 if (DEBUG_COND) {
2466 std::cout << "\nv = " << v << "\n";
2467
2468 }
2469#endif
2470 // XXX efficiently adapt to shadow leaders using neighAhead by iteration over the whole edge in parallel (lanechanger-style)
2471 if (myLaneChangeModel->getShadowLane() != nullptr) {
2472 // also slow down for leaders on the shadowLane relative to the current lane
2473 const MSLane* shadowLane = myLaneChangeModel->getShadowLane(leaderLane);
2474 if (shadowLane != nullptr
2475 && (MSGlobals::gLateralResolution > 0 || getLateralOverlap() > POSITION_EPS
2476 // continous lane change cannot be stopped so we must adapt to the leader on the target lane
2478 if ((&shadowLane->getEdge() == &leaderLane->getEdge() || myLaneChangeModel->isOpposite())) {
2481 // ego posLat is added when retrieving sublanes but it
2482 // should be negated (subtract twice to compensate)
2483 latOffset = ((myLane->getWidth() + shadowLane->getWidth()) * 0.5
2484 - 2 * getLateralPositionOnLane());
2485
2486 }
2487 MSLeaderInfo shadowLeaders = shadowLane->getLastVehicleInformation(this, latOffset, lane->getLength() - seen);
2488#ifdef DEBUG_PLAN_MOVE
2490 std::cout << SIMTIME << " opposite veh=" << getID() << " shadowLane=" << shadowLane->getID() << " latOffset=" << latOffset << " shadowLeaders=" << shadowLeaders.toString() << "\n";
2491 }
2492#endif
2494 // ignore oncoming vehicles on the shadow lane
2495 shadowLeaders.removeOpposite(shadowLane);
2496 }
2497 const double turningDifference = MAX2(0.0, leaderLane->getLength() - shadowLane->getLength());
2498 adaptToLeaders(shadowLeaders, latOffset, seen - turningDifference, lastLink, shadowLane, v, vLinkPass);
2499 } else if (shadowLane == myLaneChangeModel->getShadowLane() && leaderLane == myLane) {
2500 // check for leader vehicles driving in the opposite direction on the opposite-direction shadow lane
2501 // (and thus in the same direction as ego)
2502 MSLeaderDistanceInfo shadowLeaders = shadowLane->getFollowersOnConsecutive(this, myLane->getOppositePos(getPositionOnLane()), true);
2503 const double latOffset = 0;
2504#ifdef DEBUG_PLAN_MOVE
2505 if (DEBUG_COND) {
2506 std::cout << SIMTIME << " opposite shadows veh=" << getID() << " shadowLane=" << shadowLane->getID()
2507 << " latOffset=" << latOffset << " shadowLeaders=" << shadowLeaders.toString() << "\n";
2508 }
2509#endif
2510 shadowLeaders.fixOppositeGaps(true);
2511#ifdef DEBUG_PLAN_MOVE
2512 if (DEBUG_COND) {
2513 std::cout << " shadowLeadersFixed=" << shadowLeaders.toString() << "\n";
2514 }
2515#endif
2516 adaptToLeaderDistance(shadowLeaders, latOffset, seen, lastLink, v, vLinkPass);
2517 }
2518 }
2519 }
2520 // adapt to pedestrians on the same lane
2521 if (lane->getEdge().getPersons().size() > 0 && lane->hasPedestrians()) {
2522 const double relativePos = lane->getLength() - seen;
2523#ifdef DEBUG_PLAN_MOVE
2524 if (DEBUG_COND) {
2525 std::cout << SIMTIME << " adapt to pedestrians on lane=" << lane->getID() << " relPos=" << relativePos << "\n";
2526 }
2527#endif
2528 const double stopTime = MAX2(1.0, ceil(getSpeed() / cfModel.getMaxDecel()));
2529 PersonDist leader = lane->nextBlocking(relativePos,
2530 getRightSideOnLane(lane), getRightSideOnLane(lane) + getVehicleType().getWidth(), stopTime);
2531 if (leader.first != 0) {
2532 const double stopSpeed = cfModel.stopSpeed(this, getSpeed(), leader.second - getVehicleType().getMinGap());
2533 v = MIN2(v, stopSpeed);
2534#ifdef DEBUG_PLAN_MOVE
2535 if (DEBUG_COND) {
2536 std::cout << SIMTIME << " pedLeader=" << leader.first->getID() << " dist=" << leader.second << " v=" << v << "\n";
2537 }
2538#endif
2539 }
2540 }
2541 if (lane->getBidiLane() != nullptr) {
2542 // adapt to pedestrians on the bidi lane
2543 const MSLane* bidiLane = lane->getBidiLane();
2544 if (bidiLane->getEdge().getPersons().size() > 0 && bidiLane->hasPedestrians()) {
2545 const double relativePos = seen;
2546#ifdef DEBUG_PLAN_MOVE
2547 if (DEBUG_COND) {
2548 std::cout << SIMTIME << " adapt to pedestrians on lane=" << lane->getID() << " relPos=" << relativePos << "\n";
2549 }
2550#endif
2551 const double stopTime = ceil(getSpeed() / cfModel.getMaxDecel());
2552 const double leftSideOnLane = bidiLane->getWidth() - getRightSideOnLane(lane);
2553 PersonDist leader = bidiLane->nextBlocking(relativePos,
2554 leftSideOnLane - getVehicleType().getWidth(), leftSideOnLane, stopTime, true);
2555 if (leader.first != 0) {
2556 const double stopSpeed = cfModel.stopSpeed(this, getSpeed(), leader.second - getVehicleType().getMinGap());
2557 v = MIN2(v, stopSpeed);
2558#ifdef DEBUG_PLAN_MOVE
2559 if (DEBUG_COND) {
2560 std::cout << SIMTIME << " pedLeader=" << leader.first->getID() << " dist=" << leader.second << " v=" << v << "\n";
2561 }
2562#endif
2563 }
2564 }
2565 }
2566 // adapt to vehicles blocked from (urgent) lane-changing
2567 if (!opposite && lane->getEdge().hasLaneChanger()) {
2568 const double vHelp = myLaneChangeModel->getCooperativeHelpSpeed(lane, seen);
2569#ifdef DEBUG_PLAN_MOVE
2570 if (DEBUG_COND && vHelp < v) {
2571 std::cout << SIMTIME << " applying cooperativeHelpSpeed v=" << vHelp << "\n";
2572 }
2573#endif
2574 v = MIN2(v, vHelp);
2575 }
2576
2577 // process all stops and waypoints on the current edge
2578 bool foundRealStop = false;
2579 while (stopIt != myStops.end()
2580 && ((&stopIt->lane->getEdge() == &lane->getEdge())
2581 || (stopIt->isOpposite && stopIt->lane->getEdge().getOppositeEdge() == &lane->getEdge()))
2582 // ignore stops that occur later in a looped route
2583 && stopIt->edge == myCurrEdge + view) {
2584 double stopDist = std::numeric_limits<double>::max();
2585 const MSStop& stop = *stopIt;
2586 const bool isFirstStop = stopIt == myStops.begin();
2587 stopIt++;
2588 if (!stop.reached || (stop.getSpeed() > 0 && keepStopping())) {
2589 // we are approaching a stop on the edge; must not drive further
2590 bool isWaypoint = stop.getSpeed() > 0;
2591 double endPos = stop.getEndPos(*this) + NUMERICAL_EPS;
2592 if (stop.parkingarea != nullptr) {
2593 // leave enough space so parking vehicles can exit
2594 const double brakePos = getBrakeGap() + lane->getLength() - seen;
2595 endPos = stop.parkingarea->getLastFreePosWithReservation(t, *this, brakePos);
2596 } else if (isWaypoint && !stop.reached) {
2597 endPos = stop.pars.startPos;
2598 }
2599 stopDist = seen + endPos - lane->getLength();
2600#ifdef DEBUG_STOPS
2601 if (DEBUG_COND) {
2602 std::cout << SIMTIME << " veh=" << getID() << " stopDist=" << stopDist << " stopLane=" << stop.lane->getID() << " stopEndPos=" << endPos << "\n";
2603 }
2604#endif
2605 double stopSpeed = laneMaxV;
2606 if (isWaypoint) {
2607 bool waypointWithStop = false;
2608 if (stop.getUntil() > t) {
2609 // check if we have to slow down or even stop
2610 SUMOTime time2end = 0;
2611 if (stop.reached) {
2612 time2end = TIME2STEPS((stop.pars.endPos - myState.myPos) / stop.getSpeed());
2613 } else {
2614 time2end = TIME2STEPS(
2615 // time to reach waypoint start
2616 stopDist / ((getSpeed() + stop.getSpeed()) / 2)
2617 // time to reach waypoint end
2618 + (stop.pars.endPos - stop.pars.startPos) / stop.getSpeed());
2619 }
2620 if (stop.getUntil() > t + time2end) {
2621 // we need to stop
2622 double distToEnd = stopDist;
2623 if (!stop.reached) {
2624 distToEnd += stop.pars.endPos - stop.pars.startPos;
2625 }
2626 stopSpeed = MAX2(cfModel.stopSpeed(this, getSpeed(), distToEnd), vMinComfortable);
2627 waypointWithStop = true;
2628 if (stopSpeed <= SUMO_const_haltingSpeed) {
2629 const_cast<MSStop&>(stop).waypointWithStop = true;
2630 }
2631 }
2632 }
2633 if (stop.reached) {
2634 stopSpeed = MIN2(stop.getSpeed(), stopSpeed);
2635 if (myState.myPos >= stop.pars.endPos && !waypointWithStop) {
2636 stopDist = std::numeric_limits<double>::max();
2637 }
2638 } else {
2639 stopSpeed = MIN2(MAX2(cfModel.freeSpeed(this, getSpeed(), stopDist, stop.getSpeed()), vMinComfortable), stopSpeed);
2640 if (!stop.reached) {
2641 stopDist += stop.pars.endPos - stop.pars.startPos;
2642 }
2643 if (lastLink != nullptr) {
2644 lastLink->adaptLeaveSpeed(cfModel.freeSpeed(this, vLinkPass, endPos, stop.getSpeed(), false, MSCFModel::CalcReason::FUTURE));
2645 }
2646 }
2647 } else {
2648 stopSpeed = cfModel.stopSpeed(this, getSpeed(), stopDist);
2649 if (!instantStopping()) {
2650 // regular stops are not emergencies
2651 stopSpeed = MAX2(stopSpeed, vMinComfortable);
2653 std::vector<std::pair<SUMOTime, double> > speedTimeLine;
2654 speedTimeLine.push_back(std::make_pair(SIMSTEP, getSpeed()));
2655 speedTimeLine.push_back(std::make_pair(SIMSTEP + DELTA_T, stopSpeed));
2656 myInfluencer->setSpeedTimeLine(speedTimeLine);
2657 }
2658 if (lastLink != nullptr) {
2659 lastLink->adaptLeaveSpeed(cfModel.stopSpeed(this, vLinkPass, endPos, MSCFModel::CalcReason::FUTURE));
2660 }
2661 }
2662 if (stopSpeed < getSpeed() && getSpeed() > SUMO_const_haltingSpeed) {
2663 // only discount braking-for-stop timeLoss if we are actually braking
2664 newStopSpeed = MIN2(newStopSpeed, stopSpeed);
2665 } else if (getSpeed() < SUMO_const_haltingSpeed) {
2666 // blocked from entering a stop
2667 newStopSpeed = std::numeric_limits<double>::max();
2668 }
2669 v = MIN2(v, stopSpeed);
2670 if (lane->isInternal()) {
2671 std::vector<MSLink*>::const_iterator exitLink = MSLane::succLinkSec(*this, view + 1, *lane, bestLaneConts);
2672 assert(!lane->isLinkEnd(exitLink));
2673 bool dummySetRequest;
2674 double dummyVLinkWait;
2675 checkLinkLeaderCurrentAndParallel(*exitLink, lane, seen, lastLink, v, vLinkPass, dummyVLinkWait, dummySetRequest);
2676 }
2677
2678#ifdef DEBUG_PLAN_MOVE
2679 if (DEBUG_COND) {
2680 std::cout << "\n" << SIMTIME << " next stop: distance = " << stopDist << " requires stopSpeed = " << stopSpeed << "\n";
2681
2682 }
2683#endif
2684 if (isFirstStop) {
2685 newStopDist = stopDist;
2686 // if the vehicle is going to stop we don't need to look further
2687 // (except for trains that make use of further link-approach registration for safety purposes)
2688 if (!isWaypoint) {
2689 planningToStop = true;
2690 if (!isRail()) {
2691 lfLinks.emplace_back(v, stopDist);
2692 foundRealStop = true;
2693 break;
2694 }
2695 }
2696 }
2697 }
2698 }
2699 if (foundRealStop) {
2700 break;
2701 }
2702
2703 // move to next lane
2704 // get the next link used
2705 std::vector<MSLink*>::const_iterator link = MSLane::succLinkSec(*this, view + 1, *lane, bestLaneConts);
2706 if (lane->isLinkEnd(link) && myLaneChangeModel->hasBlueLight() && myCurrEdge != myRoute->end() - 1) {
2707 // emergency vehicle is on the wrong lane. Obtain the link that it would use from the correct turning lane
2708 const int currentIndex = lane->getIndex();
2709 const MSLane* bestJump = nullptr;
2710 for (const LaneQ& preb : getBestLanes()) {
2711 if (preb.allowsContinuation &&
2712 (bestJump == nullptr
2713 || abs(currentIndex - preb.lane->getIndex()) < abs(currentIndex - bestJump->getIndex()))) {
2714 bestJump = preb.lane;
2715 }
2716 }
2717 if (bestJump != nullptr) {
2718 const MSEdge* nextEdge = *(myCurrEdge + 1);
2719 for (auto cand_it = bestJump->getLinkCont().begin(); cand_it != bestJump->getLinkCont().end(); cand_it++) {
2720 if (&(*cand_it)->getLane()->getEdge() == nextEdge) {
2721 link = cand_it;
2722 break;
2723 }
2724 }
2725 }
2726 }
2727
2728 // Check whether this is a turn (to save info about the next upcoming turn)
2729 if (!encounteredTurn) {
2730 if (!lane->isLinkEnd(link) && lane->getLinkCont().size() > 1) {
2731 LinkDirection linkDir = (*link)->getDirection();
2732 switch (linkDir) {
2735 break;
2736 default:
2737 nextTurn.first = seen;
2738 nextTurn.second = *link;
2739 encounteredTurn = true;
2740#ifdef DEBUG_NEXT_TURN
2741 if (DEBUG_COND) {
2742 std::cout << SIMTIME << " veh '" << getID() << "' nextTurn: " << toString(linkDir)
2743 << " at " << nextTurn.first << "m." << std::endl;
2744 }
2745#endif
2746 }
2747 }
2748 }
2749
2750 // check whether the vehicle is on its final edge
2751 if (myCurrEdge + view + 1 == myRoute->end()
2752 || (myParameter->arrivalEdge >= 0 && getRoutePosition() + view == myParameter->arrivalEdge)) {
2753 const double arrivalSpeed = (myParameter->arrivalSpeedProcedure == ArrivalSpeedDefinition::GIVEN ?
2754 myParameter->arrivalSpeed : laneMaxV);
2755 // subtract the arrival speed from the remaining distance so we get one additional driving step with arrival speed
2756 // XXX: This does not work for ballistic update refs #2579
2757 const double distToArrival = seen + myArrivalPos - lane->getLength() - SPEED2DIST(arrivalSpeed);
2758 const double va = MAX2(NUMERICAL_EPS, cfModel.freeSpeed(this, getSpeed(), distToArrival, arrivalSpeed));
2759 v = MIN2(v, va);
2760 if (lastLink != nullptr) {
2761 lastLink->adaptLeaveSpeed(va);
2762 }
2763 lfLinks.push_back(DriveProcessItem(v, seen, lane->getEdge().isFringe() ? 1000 : 0));
2764 break;
2765 }
2766 // check whether the lane or the shadowLane is a dead end (allow some leeway on intersections)
2767 if (lane->isLinkEnd(link)
2768 || (MSGlobals::gSublane && brakeForOverlap(*link, lane))
2769 || (opposite && (*link)->getViaLaneOrLane()->getParallelOpposite() == nullptr
2771 double va = cfModel.stopSpeed(this, getSpeed(), seen);
2772 if (lastLink != nullptr) {
2773 lastLink->adaptLeaveSpeed(va);
2774 }
2777 } else {
2778 v = MIN2(va, v);
2779 }
2780#ifdef DEBUG_PLAN_MOVE
2781 if (DEBUG_COND) {
2782 std::cout << " braking for link end lane=" << lane->getID() << " seen=" << seen
2783 << " overlap=" << getLateralOverlap() << " va=" << va << " committed=" << myLaneChangeModel->getCommittedSpeed() << " v=" << v << "\n";
2784
2785 }
2786#endif
2787 if (lane->isLinkEnd(link)) {
2788 lfLinks.emplace_back(v, seen);
2789 break;
2790 }
2791 }
2792 lateralShift += (*link)->getLateralShift();
2793 const bool yellowOrRed = (*link)->haveRed() || (*link)->haveYellow();
2794 // We distinguish 3 cases when determining the point at which a vehicle stops:
2795 // - allway_stop: the vehicle should stop close to the stop line but may stop at larger distance
2796 // - red/yellow light: here the vehicle 'knows' that it will have priority eventually and does not need to stop on a precise spot
2797 // - other types of minor links: the vehicle needs to stop as close to the junction as necessary
2798 // to minimize the time window for passing the junction. If the
2799 // vehicle 'decides' to accelerate and cannot enter the junction in
2800 // the next step, new foes may appear and cause a collision (see #1096)
2801 // - major links: stopping point is irrelevant
2802 double laneStopOffset;
2803 const double majorStopOffset = MAX2(getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_GAP, DIST_TO_STOPLINE_EXPECT_PRIORITY), lane->getVehicleStopOffset(this));
2804 // override low desired decel at yellow and red
2805 const double stopDecel = yellowOrRed && !isRail() ? MAX2(MIN2(MSGlobals::gTLSYellowMinDecel, cfModel.getEmergencyDecel()), cfModel.getMaxDecel()) : cfModel.getMaxDecel();
2806 const double brakeDist = cfModel.brakeGap(myState.mySpeed, stopDecel, 0);
2807 const bool canBrakeBeforeLaneEnd = seen >= brakeDist;
2808 const bool canBrakeBeforeStopLine = seen - lane->getVehicleStopOffset(this) >= brakeDist;
2809 if (yellowOrRed) {
2810 // Wait at red traffic light with full distance if possible
2811 laneStopOffset = majorStopOffset;
2812 } else if ((*link)->havePriority()) {
2813 // On priority link, we should never stop below visibility distance
2814 laneStopOffset = MIN2((*link)->getFoeVisibilityDistance() - POSITION_EPS, majorStopOffset);
2815 } else {
2816 double minorStopOffset = MAX2(lane->getVehicleStopOffset(this),
2817 getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_CROSSING_GAP, MSPModel::SAFETY_GAP) - (*link)->getDistToFoePedCrossing());
2818#ifdef DEBUG_PLAN_MOVE
2819 if (DEBUG_COND) {
2820 std::cout << " minorStopOffset=" << minorStopOffset << " distToFoePedCrossing=" << (*link)->getDistToFoePedCrossing() << "\n";
2821 }
2822#endif
2823 if ((*link)->getState() == LINKSTATE_ALLWAY_STOP) {
2824 minorStopOffset = MAX2(minorStopOffset, getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_GAP, 0));
2825 } else {
2826 minorStopOffset = MAX2(minorStopOffset, getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_GAP_MINOR, 0));
2827 }
2828 // On minor link, we should likewise never stop below visibility distance
2829 laneStopOffset = MIN2((*link)->getFoeVisibilityDistance() - POSITION_EPS, minorStopOffset);
2830 }
2831#ifdef DEBUG_PLAN_MOVE
2832 if (DEBUG_COND) {
2833 std::cout << SIMTIME << " veh=" << getID() << " desired stopOffset on lane '" << lane->getID() << "' is " << laneStopOffset << "\n";
2834 }
2835#endif
2836 if (canBrakeBeforeLaneEnd) {
2837 // avoid emergency braking if possible
2838 laneStopOffset = MIN2(laneStopOffset, seen - brakeDist);
2839 }
2840 laneStopOffset = MAX2(POSITION_EPS, laneStopOffset);
2841 double stopDist = MAX2(0., seen - laneStopOffset);
2842 if (yellowOrRed && getDevice(typeid(MSDevice_GLOSA)) != nullptr
2843 && static_cast<MSDevice_GLOSA*>(getDevice(typeid(MSDevice_GLOSA)))->getOverrideSafety()
2844 && static_cast<MSDevice_GLOSA*>(getDevice(typeid(MSDevice_GLOSA)))->isSpeedAdviceActive()) {
2845 stopDist = std::numeric_limits<double>::max();
2846 }
2847 if (newStopDist != std::numeric_limits<double>::max()) {
2848 stopDist = MAX2(stopDist, newStopDist);
2849 }
2850#ifdef DEBUG_PLAN_MOVE
2851 if (DEBUG_COND) {
2852 std::cout << SIMTIME << " veh=" << getID() << " effective stopOffset on lane '" << lane->getID()
2853 << "' is " << laneStopOffset << " (-> stopDist=" << stopDist << ")" << std::endl;
2854 }
2855#endif
2856 if (isRail() && !lane->isInternal()) {
2857 // check for train direction reversal
2858 if (lane->getBidiLane() != nullptr
2859 && (*link)->getLane()->getBidiLane() == lane) {
2860 double vMustReverse = getCarFollowModel().stopSpeed(this, getSpeed(), seen - NUMERICAL_EPS);
2861 if (seen < 1) {
2862 mustSeeBeforeReversal = 2 * seen + getLength();
2863 }
2864 v = MIN2(v, vMustReverse);
2865 }
2866 // signal that is passed in the current step does not count
2867 foundRailSignal |= ((*link)->getTLLogic() != nullptr
2868 && (*link)->getTLLogic()->getLogicType() == TrafficLightType::RAIL_SIGNAL
2869 && seen > SPEED2DIST(v));
2870 }
2871
2872 if (!planningToStop) {
2873 // no need to slow down for reversal if we are alrady slowing down for a stop
2874 bool canReverseEventually = false;
2875 const double vReverse = checkReversal(canReverseEventually, laneMaxV, seen);
2876 v = MIN2(v, vReverse);
2877#ifdef DEBUG_PLAN_MOVE
2878 if (DEBUG_COND) {
2879 std::cout << SIMTIME << " veh=" << getID() << " canReverseEventually=" << canReverseEventually << " v=" << v << "\n";
2880 }
2881#endif
2882 }
2883
2884 // check whether we need to slow down in order to finish a continuous lane change
2886 if ( // slow down to finish lane change before a turn lane
2887 ((*link)->getDirection() == LinkDirection::LEFT || (*link)->getDirection() == LinkDirection::RIGHT) ||
2888 // slow down to finish lane change before the shadow lane ends
2889 (myLaneChangeModel->getShadowLane() != nullptr &&
2890 (*link)->getViaLaneOrLane()->getParallelLane(myLaneChangeModel->getShadowDirection()) == nullptr)) {
2891 // XXX maybe this is too harsh. Vehicles could cut some corners here
2892 const double timeRemaining = STEPS2TIME(myLaneChangeModel->remainingTime());
2893 assert(timeRemaining != 0);
2894 // XXX: Euler-logic (#860), but I couldn't identify problems from this yet (Leo). Refs. #2575
2895 const double va = MAX2(cfModel.stopSpeed(this, getSpeed(), seen - POSITION_EPS),
2896 (seen - POSITION_EPS) / timeRemaining);
2897#ifdef DEBUG_PLAN_MOVE
2898 if (DEBUG_COND) {
2899 std::cout << SIMTIME << " veh=" << getID() << " slowing down to finish continuous change before"
2900 << " link=" << (*link)->getViaLaneOrLane()->getID()
2901 << " timeRemaining=" << timeRemaining
2902 << " v=" << v
2903 << " va=" << va
2904 << std::endl;
2905 }
2906#endif
2907 v = MIN2(va, v);
2908 }
2909 }
2910
2911 // - always issue a request to leave the intersection we are currently on
2912 const bool leavingCurrentIntersection = myLane->getEdge().isInternal() && lastLink == nullptr;
2913 // - do not issue a request to enter an intersection after we already slowed down for an earlier one
2914 const bool abortRequestAfterMinor = slowedDownForMinor && (*link)->getInternalLaneBefore() == nullptr;
2915 // - even if red, if we cannot break we should issue a request
2916 bool setRequest = (v > NUMERICAL_EPS_SPEED && !abortRequestAfterMinor) || (leavingCurrentIntersection);
2917
2918 double stopSpeed = cfModel.stopSpeed(this, getSpeed(), stopDist, stopDecel, MSCFModel::CalcReason::CURRENT_WAIT);
2919 double vLinkWait = MIN2(v, stopSpeed);
2920#ifdef DEBUG_PLAN_MOVE
2921 if (DEBUG_COND) {
2922 std::cout
2923 << " stopDist=" << stopDist
2924 << " stopDecel=" << stopDecel
2925 << " vLinkWait=" << vLinkWait
2926 << " brakeDist=" << brakeDist
2927 << " seen=" << seen
2928 << " leaveIntersection=" << leavingCurrentIntersection
2929 << " setRequest=" << setRequest
2930 //<< std::setprecision(16)
2931 //<< " v=" << v
2932 //<< " speedEps=" << NUMERICAL_EPS_SPEED
2933 //<< std::setprecision(gPrecision)
2934 << "\n";
2935 }
2936#endif
2937
2938 if (yellowOrRed && canBrakeBeforeStopLine && !ignoreRed(*link, canBrakeBeforeStopLine) && seen >= mustSeeBeforeReversal) {
2939 if (lane->isInternal()) {
2940 checkLinkLeaderCurrentAndParallel(*link, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest);
2941 }
2942 // arrivalSpeed / arrivalTime when braking for red light is only relevent for rail signal switching
2943 const SUMOTime arrivalTime = getArrivalTime(t, seen, v, vLinkPass);
2944 // the vehicle is able to brake in front of a yellow/red traffic light
2945 lfLinks.push_back(DriveProcessItem(*link, v, vLinkWait, false, arrivalTime, vLinkWait, 0, seen, -1));
2946 //lfLinks.push_back(DriveProcessItem(0, vLinkWait, vLinkWait, false, 0, 0, stopDist));
2947 break;
2948 }
2949
2950 const MSLink* entryLink = (*link)->getCorrespondingEntryLink();
2951 if (entryLink->haveRed() && ignoreRed(*link, canBrakeBeforeStopLine) && STEPS2TIME(t - entryLink->getLastStateChange()) > 2) {
2952 // restrict speed when ignoring a red light
2953 const double redSpeed = MIN2(v, getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_DRIVE_RED_SPEED, v));
2954 const double va = MAX2(redSpeed, cfModel.freeSpeed(this, getSpeed(), seen, redSpeed));
2955 v = MIN2(va, v);
2956#ifdef DEBUG_PLAN_MOVE
2957 if (DEBUG_COND) std::cout
2958 << " ignoreRed spent=" << STEPS2TIME(t - (*link)->getLastStateChange())
2959 << " redSpeed=" << redSpeed
2960 << " va=" << va
2961 << " v=" << v
2962 << "\n";
2963#endif
2964 }
2965
2966 checkLinkLeaderCurrentAndParallel(*link, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest);
2967
2968 if (lastLink != nullptr) {
2969 lastLink->adaptLeaveSpeed(laneMaxV);
2970 }
2971 double arrivalSpeed = vLinkPass;
2972 // vehicles should decelerate when approaching a minor link
2973 // - unless they are close enough to have clear visibility of all relevant foe lanes and may start to accelerate again
2974 // - and unless they are so close that stopping is impossible (i.e. when a green light turns to yellow when close to the junction)
2975
2976 // whether the vehicle/driver is close enough to the link to see all possible foes #2123
2977 const double visibilityDistance = (*link)->getFoeVisibilityDistance();
2978 const double determinedFoePresence = seen <= visibilityDistance;
2979// // VARIANT: account for time needed to recognize whether relevant vehicles are on the foe lanes. (Leo)
2980// double foeRecognitionTime = 0.0;
2981// double determinedFoePresence = seen < visibilityDistance - myState.mySpeed*foeRecognitionTime;
2982
2983#ifdef DEBUG_PLAN_MOVE
2984 if (DEBUG_COND) {
2985 std::cout << " approaching link=" << (*link)->getViaLaneOrLane()->getID() << " prio=" << (*link)->havePriority() << " seen=" << seen << " visibilityDistance=" << visibilityDistance << " brakeDist=" << brakeDist << "\n";
2986 }
2987#endif
2988
2989 const bool couldBrakeForMinor = !(*link)->havePriority() && brakeDist < seen && !(*link)->lastWasContMajor();
2990 if (couldBrakeForMinor && !determinedFoePresence) {
2991 // vehicle decelerates just enough to be able to stop if necessary and then accelerates
2992 double maxSpeedAtVisibilityDist = cfModel.maximumSafeStopSpeed(visibilityDistance, cfModel.getMaxDecel(), myState.mySpeed, false, 0., false);
2993 // XXX: estimateSpeedAfterDistance does not use euler-logic (thus returns a lower value than possible here...)
2994 double maxArrivalSpeed = cfModel.estimateSpeedAfterDistance(visibilityDistance, maxSpeedAtVisibilityDist, cfModel.getMaxAccel());
2995 arrivalSpeed = MIN2(vLinkPass, maxArrivalSpeed);
2996 slowedDownForMinor = true;
2997#ifdef DEBUG_PLAN_MOVE
2998 if (DEBUG_COND) {
2999 std::cout << " slowedDownForMinor maxSpeedAtVisDist=" << maxSpeedAtVisibilityDist << " maxArrivalSpeed=" << maxArrivalSpeed << " arrivalSpeed=" << arrivalSpeed << "\n";
3000 }
3001#endif
3002 } else if ((*link)->getState() == LINKSTATE_EQUAL && myWaitingTime > 0) {
3003 // check for deadlock (circular yielding)
3004 //std::cout << SIMTIME << " veh=" << getID() << " check rbl-deadlock\n";
3005 std::pair<const SUMOVehicle*, const MSLink*> blocker = (*link)->getFirstApproachingFoe(*link);
3006 //std::cout << " blocker=" << Named::getIDSecure(blocker.first) << "\n";
3007 int n = 100;
3008 while (blocker.second != nullptr && blocker.second != *link && n > 0) {
3009 blocker = blocker.second->getFirstApproachingFoe(*link);
3010 n--;
3011 //std::cout << " blocker=" << Named::getIDSecure(blocker.first) << "\n";
3012 }
3013 if (n == 0) {
3014 WRITE_WARNINGF(TL("Suspicious right_before_left junction '%'."), lane->getEdge().getToJunction()->getID());
3015 }
3016 //std::cout << " blockerLink=" << blocker.second << " link=" << *link << "\n";
3017 if (blocker.second == *link) {
3018 const double threshold = (*link)->getDirection() == LinkDirection::STRAIGHT ? 0.25 : 0.75;
3019 if (RandHelper::rand(getRNG()) < threshold) {
3020 //std::cout << " abort request, threshold=" << threshold << "\n";
3021 setRequest = false;
3022 }
3023 }
3024 }
3025
3026 const SUMOTime arrivalTime = getArrivalTime(t, seen, v, arrivalSpeed);
3027 if (couldBrakeForMinor && determinedFoePresence && (*link)->getLane()->getEdge().isRoundabout()) {
3028 const bool wasOpened = (*link)->opened(arrivalTime, arrivalSpeed, arrivalSpeed,
3030 getCarFollowModel().getMaxDecel(),
3032 nullptr, false, this);
3033 if (!wasOpened) {
3034 slowedDownForMinor = true;
3035 }
3036#ifdef DEBUG_PLAN_MOVE
3037 if (DEBUG_COND) {
3038 std::cout << " slowedDownForMinor at roundabout=" << (!wasOpened) << "\n";
3039 }
3040#endif
3041 }
3042
3043 // compute arrival speed and arrival time if vehicle starts braking now
3044 // if stopping is possible, arrivalTime can be arbitrarily large. A small value keeps fractional times (impatience) meaningful
3045 double arrivalSpeedBraking = 0;
3046 const double bGap = cfModel.brakeGap(v);
3047 if (seen < bGap && !isStopped() && !planningToStop) { // XXX: should this use the current speed (at least for the ballistic case)? (Leo) Refs. #2575
3048 // vehicle cannot come to a complete stop in time
3050 arrivalSpeedBraking = cfModel.getMinimalArrivalSpeedEuler(seen, v);
3051 // due to discrete/continuous mismatch (when using Euler update) we have to ensure that braking actually helps
3052 arrivalSpeedBraking = MIN2(arrivalSpeedBraking, arrivalSpeed);
3053 } else {
3054 arrivalSpeedBraking = cfModel.getMinimalArrivalSpeed(seen, myState.mySpeed);
3055 }
3056 }
3057
3058 // estimate leave speed for passing time computation
3059 // l=linkLength, a=accel, t=continuousTime, v=vLeave
3060 // l=v*t + 0.5*a*t^2, solve for t and multiply with a, then add v
3061 const double estimatedLeaveSpeed = MIN2((*link)->getViaLaneOrLane()->getVehicleMaxSpeed(this, maxVD),
3062 getCarFollowModel().estimateSpeedAfterDistance((*link)->getLength(), arrivalSpeed, getVehicleType().getCarFollowModel().getMaxAccel()));
3063 lfLinks.push_back(DriveProcessItem(*link, v, vLinkWait, setRequest,
3064 arrivalTime, arrivalSpeed,
3065 arrivalSpeedBraking,
3066 seen, estimatedLeaveSpeed));
3067 if ((*link)->getViaLane() == nullptr) {
3068 hadNonInternal = true;
3069 ++view;
3070 }
3071#ifdef DEBUG_PLAN_MOVE
3072 if (DEBUG_COND) {
3073 std::cout << " checkAbort setRequest=" << setRequest << " v=" << v << " seen=" << seen << " dist=" << dist
3074 << " seenNonInternal=" << seenNonInternal
3075 << " seenInternal=" << seenInternal << " length=" << vehicleLength << "\n";
3076 }
3077#endif
3078 // we need to look ahead far enough to see available space for checkRewindLinkLanes
3079 if ((!setRequest || v <= 0 || seen > dist) && hadNonInternal && seenNonInternal > MAX2(vehicleLength * CRLL_LOOK_AHEAD, vehicleLength + seenInternal) && foundRailSignal) {
3080 break;
3081 }
3082 // get the following lane
3083 lane = (*link)->getViaLaneOrLane();
3084 laneMaxV = lane->getVehicleMaxSpeed(this, maxVD);
3086 laneMaxV = std::numeric_limits<double>::max();
3087 }
3088 // the link was passed
3089 // compute the velocity to use when the link is not blocked by other vehicles
3090 // the vehicle shall be not faster when reaching the next lane than allowed
3091 // speed limits are not emergencies (e.g. when the limit changes suddenly due to TraCI or a variableSpeedSignal)
3092 const double va = MAX2(cfModel.freeSpeed(this, getSpeed(), seen, laneMaxV), vMinComfortable - NUMERICAL_EPS);
3093 v = MIN2(va, v);
3094#ifdef DEBUG_PLAN_MOVE
3095 if (DEBUG_COND) {
3096 std::cout << " laneMaxV=" << laneMaxV << " freeSpeed=" << va << " v=" << v << "\n";
3097 }
3098#endif
3099 if (lane->getEdge().isInternal()) {
3100 seenInternal += lane->getLength();
3101 } else {
3102 seenNonInternal += lane->getLength();
3103 }
3104 // do not restrict results to the current vehicle to allow caching for the current time step
3105 leaderLane = opposite ? lane->getParallelOpposite() : lane;
3106 if (leaderLane == nullptr) {
3107
3108 break;
3109 }
3110 ahead = opposite ? MSLeaderInfo(leaderLane->getWidth()) : leaderLane->getLastVehicleInformation(nullptr, 0);
3111 seen += lane->getLength();
3112 vLinkPass = MIN2(cfModel.estimateSpeedAfterDistance(lane->getLength(), v, cfModel.getMaxAccel()), laneMaxV); // upper bound
3113 lastLink = &lfLinks.back();
3114 }
3115
3116//#ifdef DEBUG_PLAN_MOVE
3117// if(DEBUG_COND){
3118// std::cout << "planMoveInternal found safe speed v = " << v << std::endl;
3119// }
3120//#endif
3121
3122#ifdef PARALLEL_STOPWATCH
3123 myLane->getStopWatch()[0].stop();
3124#endif
3125}
3126
3127
3128double
3129MSVehicle::slowDownForSchedule(double vMinComfortable) const {
3130 const double sfp = getVehicleType().getParameter().speedFactorPremature;
3131 const MSStop& stop = myStops.front();
3132 std::pair<double, double> timeDist = estimateTimeToNextStop();
3133 double arrivalDelay = SIMTIME + timeDist.first - STEPS2TIME(stop.pars.arrival);
3134 double t = STEPS2TIME(stop.pars.arrival - SIMSTEP);
3137 arrivalDelay += STEPS2TIME(stop.pars.arrival - flexStart);
3138 t = STEPS2TIME(flexStart - SIMSTEP);
3139 } else if (stop.pars.started >= 0 && MSGlobals::gUseStopStarted) {
3140 arrivalDelay += STEPS2TIME(stop.pars.arrival - stop.pars.started);
3141 t = STEPS2TIME(stop.pars.started - SIMSTEP);
3142 }
3143 if (arrivalDelay < 0 && sfp < getChosenSpeedFactor()) {
3144 // we can slow down to better match the schedule (and increase energy efficiency)
3145 const double vSlowDownMin = MAX2(myLane->getSpeedLimit() * sfp, vMinComfortable);
3146 const double s = timeDist.second;
3147 const double b = getCarFollowModel().getMaxDecel();
3148 // x = speed for arriving in t seconds
3149 // u = time at full speed
3150 // u * x + (t - u) * 0.5 * x = s
3151 // t - u = x / b
3152 // eliminate u, solve x
3153 const double radicand = 4 * t * t * b * b - 8 * s * b;
3154 const double x = radicand >= 0 ? t * b - sqrt(radicand) * 0.5 : vSlowDownMin;
3155 double vSlowDown = x < vSlowDownMin ? vSlowDownMin : x;
3156#ifdef DEBUG_PLAN_MOVE
3157 if (DEBUG_COND) {
3158 std::cout << SIMTIME << " veh=" << getID() << " ad=" << arrivalDelay << " t=" << t << " vsm=" << vSlowDownMin
3159 << " r=" << radicand << " vs=" << vSlowDown << "\n";
3160 }
3161#endif
3162 return vSlowDown;
3163 } else if (arrivalDelay > 0 && sfp > getChosenSpeedFactor()) {
3164 // in principle we could up to catch up with the schedule
3165 // but at this point we can only lower the speed, the
3166 // information would have to be used when computing getVehicleMaxSpeed
3167 }
3168 return getMaxSpeed();
3169}
3170
3172MSVehicle::getArrivalTime(SUMOTime t, double seen, double v, double arrivalSpeed) const {
3173 const MSCFModel& cfModel = getCarFollowModel();
3174 SUMOTime arrivalTime;
3176 // @note intuitively it would make sense to compare arrivalSpeed with getSpeed() instead of v
3177 // however, due to the current position update rule (ticket #860) the vehicle moves with v in this step
3178 // subtract DELTA_T because t is the time at the end of this step and the movement is not carried out yet
3179 arrivalTime = t - DELTA_T + cfModel.getMinimalArrivalTime(seen, v, arrivalSpeed);
3180 } else {
3181 arrivalTime = t - DELTA_T + cfModel.getMinimalArrivalTime(seen, myState.mySpeed, arrivalSpeed);
3182 }
3183 if (isStopped()) {
3184 arrivalTime += MAX2((SUMOTime)0, myStops.front().duration);
3185 }
3186 return arrivalTime;
3187}
3188
3189
3190void
3191MSVehicle::adaptToLeaders(const MSLeaderInfo& ahead, double latOffset,
3192 const double seen, DriveProcessItem* const lastLink,
3193 const MSLane* const lane, double& v, double& vLinkPass) const {
3194 int rightmost;
3195 int leftmost;
3196 ahead.getSubLanes(this, latOffset, rightmost, leftmost);
3197#ifdef DEBUG_PLAN_MOVE
3198 if (DEBUG_COND) std::cout << SIMTIME
3199 << "\nADAPT_TO_LEADERS\nveh=" << getID()
3200 << " lane=" << lane->getID()
3201 << " latOffset=" << latOffset
3202 << " rm=" << rightmost
3203 << " lm=" << leftmost
3204 << " shift=" << ahead.getSublaneOffset()
3205 << " ahead=" << ahead.toString()
3206 << "\n";
3207#endif
3208 /*
3209 if (myLaneChangeModel->getCommittedSpeed() > 0) {
3210 v = MIN2(v, myLaneChangeModel->getCommittedSpeed());
3211 vLinkPass = MIN2(vLinkPass, myLaneChangeModel->getCommittedSpeed());
3212 #ifdef DEBUG_PLAN_MOVE
3213 if (DEBUG_COND) std::cout << " hasCommitted=" << myLaneChangeModel->getCommittedSpeed() << "\n";
3214 #endif
3215 return;
3216 }
3217 */
3218 for (int sublane = rightmost; sublane <= leftmost; ++sublane) {
3219 const MSVehicle* pred = ahead[sublane];
3220 if (pred != nullptr && pred != this) {
3221 // @todo avoid multiple adaptations to the same leader
3222 const double predBack = pred->getBackPositionOnLane(lane);
3223 double gap = (lastLink == nullptr
3224 ? predBack - myState.myPos - getVehicleType().getMinGap()
3225 : predBack + seen - lane->getLength() - getVehicleType().getMinGap());
3226 bool oncoming = false;
3228 if (pred->getLaneChangeModel().isOpposite() || lane == pred->getLaneChangeModel().getShadowLane()) {
3229 // ego might and leader are driving against lane
3230 gap = (lastLink == nullptr
3231 ? myState.myPos - predBack - getVehicleType().getMinGap()
3232 : predBack + seen - lane->getLength() - getVehicleType().getMinGap());
3233 } else {
3234 // ego and leader are driving in the same direction as lane (shadowlane for ego)
3235 gap = (lastLink == nullptr
3236 ? predBack - (myLane->getLength() - myState.myPos) - getVehicleType().getMinGap()
3237 : predBack + seen - lane->getLength() - getVehicleType().getMinGap());
3238 }
3239 } else if (pred->getLaneChangeModel().isOpposite() && pred->getLaneChangeModel().getShadowLane() != lane) {
3240 // must react to stopped / dangerous oncoming vehicles
3241 gap += -pred->getVehicleType().getLength() + getVehicleType().getMinGap() - MAX2(getVehicleType().getMinGap(), pred->getVehicleType().getMinGap());
3242 // try to avoid collision in the next second
3243 const double predMaxDist = pred->getSpeed() + pred->getCarFollowModel().getMaxAccel();
3244#ifdef DEBUG_PLAN_MOVE
3245 if (DEBUG_COND) {
3246 std::cout << " fixedGap=" << gap << " predMaxDist=" << predMaxDist << "\n";
3247 }
3248#endif
3249 if (gap < predMaxDist + getSpeed() || pred->getLane() == lane->getBidiLane()) {
3250 gap -= predMaxDist;
3251 }
3252 } else if (pred->getLane() == lane->getBidiLane()) {
3253 gap -= pred->getVehicleType().getLengthWithGap();
3254 oncoming = true;
3255 }
3256#ifdef DEBUG_PLAN_MOVE
3257 if (DEBUG_COND) {
3258 std::cout << " pred=" << pred->getID() << " predLane=" << pred->getLane()->getID() << " predPos=" << pred->getPositionOnLane() << " gap=" << gap << " predBack=" << predBack << " seen=" << seen << " lane=" << lane->getID() << " myLane=" << myLane->getID() << " lastLink=" << (lastLink == nullptr ? "NULL" : lastLink->myLink->getDescription()) << " oncoming=" << oncoming << "\n";
3259 }
3260#endif
3261 if (oncoming && gap >= 0) {
3262 adaptToOncomingLeader(std::make_pair(pred, gap), lastLink, v, vLinkPass);
3263 } else {
3264 adaptToLeader(std::make_pair(pred, gap), seen, lastLink, v, vLinkPass);
3265 }
3266 }
3267 }
3268}
3269
3270void
3272 double seen,
3273 DriveProcessItem* const lastLink,
3274 double& v, double& vLinkPass) const {
3275 int rightmost;
3276 int leftmost;
3277 ahead.getSubLanes(this, latOffset, rightmost, leftmost);
3278#ifdef DEBUG_PLAN_MOVE
3279 if (DEBUG_COND) std::cout << SIMTIME
3280 << "\nADAPT_TO_LEADERS_DISTANCE\nveh=" << getID()
3281 << " latOffset=" << latOffset
3282 << " rm=" << rightmost
3283 << " lm=" << leftmost
3284 << " ahead=" << ahead.toString()
3285 << "\n";
3286#endif
3287 for (int sublane = rightmost; sublane <= leftmost; ++sublane) {
3288 CLeaderDist predDist = ahead[sublane];
3289 const MSVehicle* pred = predDist.first;
3290 if (pred != nullptr && pred != this) {
3291#ifdef DEBUG_PLAN_MOVE
3292 if (DEBUG_COND) {
3293 std::cout << " pred=" << pred->getID() << " predLane=" << pred->getLane()->getID() << " predPos=" << pred->getPositionOnLane() << " gap=" << predDist.second << "\n";
3294 }
3295#endif
3296 adaptToLeader(predDist, seen, lastLink, v, vLinkPass);
3297 }
3298 }
3299}
3300
3301
3302void
3303MSVehicle::adaptToLeader(const std::pair<const MSVehicle*, double> leaderInfo,
3304 double seen,
3305 DriveProcessItem* const lastLink,
3306 double& v, double& vLinkPass) const {
3307 if (leaderInfo.first != 0) {
3308 if (ignoreFoe(leaderInfo.first)) {
3309#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3310 if (DEBUG_COND) {
3311 std::cout << " foe ignored\n";
3312 }
3313#endif
3314 return;
3315 }
3316 const MSCFModel& cfModel = getCarFollowModel();
3317 double vsafeLeader = 0;
3319 vsafeLeader = -std::numeric_limits<double>::max();
3320 }
3321 bool backOnRoute = true;
3322 if (leaderInfo.second < 0 && lastLink != nullptr && lastLink->myLink != nullptr) {
3323 backOnRoute = false;
3324 // this can either be
3325 // a) a merging situation (leader back is is not our route) or
3326 // b) a minGap violation / collision
3327 MSLane* current = lastLink->myLink->getViaLaneOrLane();
3328 if (leaderInfo.first->getBackLane() == current) {
3329 backOnRoute = true;
3330 } else {
3331 for (MSLane* lane : getBestLanesContinuation()) {
3332 if (lane == current) {
3333 break;
3334 }
3335 if (leaderInfo.first->getBackLane() == lane) {
3336 backOnRoute = true;
3337 }
3338 }
3339 }
3340#ifdef DEBUG_PLAN_MOVE
3341 if (DEBUG_COND) {
3342 std::cout << SIMTIME << " current=" << current->getID() << " leaderBackLane=" << leaderInfo.first->getBackLane()->getID() << " backOnRoute=" << backOnRoute << "\n";
3343 }
3344#endif
3345 if (!backOnRoute) {
3346 double stopDist = seen - current->getLength() - POSITION_EPS;
3347 if (lastLink->myLink->getInternalLaneBefore() != nullptr) {
3348 // do not drive onto the junction conflict area
3349 stopDist -= lastLink->myLink->getInternalLaneBefore()->getLength();
3350 }
3351 vsafeLeader = cfModel.stopSpeed(this, getSpeed(), stopDist);
3352 }
3353 }
3354 if (backOnRoute) {
3355 vsafeLeader = cfModel.followSpeed(this, getSpeed(), leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first);
3356 }
3357 if (lastLink != nullptr) {
3358 const double futureVSafe = cfModel.followSpeed(this, lastLink->accelV, leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first, MSCFModel::CalcReason::FUTURE);
3359 lastLink->adaptLeaveSpeed(futureVSafe);
3360#ifdef DEBUG_PLAN_MOVE
3361 if (DEBUG_COND) {
3362 std::cout << " vlinkpass=" << lastLink->myVLinkPass << " futureVSafe=" << futureVSafe << "\n";
3363 }
3364#endif
3365 }
3366 v = MIN2(v, vsafeLeader);
3367 vLinkPass = MIN2(vLinkPass, vsafeLeader);
3368#ifdef DEBUG_PLAN_MOVE
3369 if (DEBUG_COND) std::cout
3370 << SIMTIME
3371 //std::cout << std::setprecision(10);
3372 << " veh=" << getID()
3373 << " lead=" << leaderInfo.first->getID()
3374 << " leadSpeed=" << leaderInfo.first->getSpeed()
3375 << " gap=" << leaderInfo.second
3376 << " leadLane=" << leaderInfo.first->getLane()->getID()
3377 << " predPos=" << leaderInfo.first->getPositionOnLane()
3378 << " myLane=" << myLane->getID()
3379 << " v=" << v
3380 << " vSafeLeader=" << vsafeLeader
3381 << " vLinkPass=" << vLinkPass
3382 << "\n";
3383#endif
3384 }
3385}
3386
3387
3388void
3389MSVehicle::adaptToJunctionLeader(const std::pair<const MSVehicle*, double> leaderInfo,
3390 const double seen, DriveProcessItem* const lastLink,
3391 const MSLane* const lane, double& v, double& vLinkPass,
3392 double distToCrossing) const {
3393 if (leaderInfo.first != 0) {
3394 if (ignoreFoe(leaderInfo.first)) {
3395#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3396 if (DEBUG_COND) {
3397 std::cout << " junction foe ignored\n";
3398 }
3399#endif
3400 return;
3401 }
3402 const MSCFModel& cfModel = getCarFollowModel();
3403 double vsafeLeader = 0;
3405 vsafeLeader = -std::numeric_limits<double>::max();
3406 }
3407 if (leaderInfo.second >= 0) {
3408 if (hasDeparted()) {
3409 vsafeLeader = cfModel.followSpeed(this, getSpeed(), leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first);
3410 } else {
3411 // called in the context of MSLane::isInsertionSuccess
3412 vsafeLeader = cfModel.insertionFollowSpeed(this, getSpeed(), leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first);
3413 }
3414 } else if (leaderInfo.first != this) {
3415 // the leading, in-lapping vehicle is occupying the complete next lane
3416 // stop before entering this lane
3417 vsafeLeader = cfModel.stopSpeed(this, getSpeed(), seen - lane->getLength() - POSITION_EPS);
3418#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3419 if (DEBUG_COND) {
3420 std::cout << SIMTIME << " veh=" << getID() << " stopping before junction: lane=" << lane->getID() << " seen=" << seen
3421 << " laneLength=" << lane->getLength()
3422 << " stopDist=" << seen - lane->getLength() - POSITION_EPS
3423 << " vsafeLeader=" << vsafeLeader
3424 << " distToCrossing=" << distToCrossing
3425 << "\n";
3426 }
3427#endif
3428 }
3429 if (distToCrossing >= 0) {
3430 // can the leader still stop in the way?
3431 const double vStop = cfModel.stopSpeed(this, getSpeed(), distToCrossing - getVehicleType().getMinGap());
3432 if (leaderInfo.first == this) {
3433 // braking for pedestrian
3434 const double vStopCrossing = cfModel.stopSpeed(this, getSpeed(), distToCrossing);
3435 vsafeLeader = vStopCrossing;
3436#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3437 if (DEBUG_COND) {
3438 std::cout << " breaking for pedestrian distToCrossing=" << distToCrossing << " vStopCrossing=" << vStopCrossing << "\n";
3439 }
3440#endif
3441 if (lastLink != nullptr) {
3442 lastLink->adaptStopSpeed(vsafeLeader);
3443 }
3444 } else if (leaderInfo.second == -std::numeric_limits<double>::max()) {
3445 // drive up to the crossing point and stop
3446#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3447 if (DEBUG_COND) {
3448 std::cout << " stop at crossing point for critical leader vStop=" << vStop << "\n";
3449 };
3450#endif
3451 vsafeLeader = MAX2(vsafeLeader, vStop);
3452 } else {
3453 const double leaderDistToCrossing = distToCrossing - leaderInfo.second;
3454 // estimate the time at which the leader has gone past the crossing point
3455 const double leaderPastCPTime = leaderDistToCrossing / MAX2(leaderInfo.first->getSpeed(), SUMO_const_haltingSpeed);
3456 // reach distToCrossing after that time
3457 // avgSpeed * leaderPastCPTime = distToCrossing
3458 // ballistic: avgSpeed = (getSpeed + vFinal) / 2
3459 const double vFinal = MAX2(getSpeed(), 2 * (distToCrossing - getVehicleType().getMinGap()) / leaderPastCPTime - getSpeed());
3460 const double v2 = getSpeed() + ACCEL2SPEED((vFinal - getSpeed()) / leaderPastCPTime);
3461 vsafeLeader = MAX2(vsafeLeader, MIN2(v2, vStop));
3462#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3463 if (DEBUG_COND) {
3464 std::cout << " driving up to the crossing point (distToCrossing=" << distToCrossing << ")"
3465 << " leaderPastCPTime=" << leaderPastCPTime
3466 << " vFinal=" << vFinal
3467 << " v2=" << v2
3468 << " vStop=" << vStop
3469 << " vsafeLeader=" << vsafeLeader << "\n";
3470 }
3471#endif
3472 }
3473 }
3474 if (lastLink != nullptr) {
3475 lastLink->adaptLeaveSpeed(vsafeLeader);
3476 }
3477 v = MIN2(v, vsafeLeader);
3478 vLinkPass = MIN2(vLinkPass, vsafeLeader);
3479#ifdef DEBUG_PLAN_MOVE
3480 if (DEBUG_COND) std::cout
3481 << SIMTIME
3482 //std::cout << std::setprecision(10);
3483 << " veh=" << getID()
3484 << " lead=" << leaderInfo.first->getID()
3485 << " leadSpeed=" << leaderInfo.first->getSpeed()
3486 << " gap=" << leaderInfo.second
3487 << " leadLane=" << leaderInfo.first->getLane()->getID()
3488 << " predPos=" << leaderInfo.first->getPositionOnLane()
3489 << " seen=" << seen
3490 << " lane=" << lane->getID()
3491 << " myLane=" << myLane->getID()
3492 << " dTC=" << distToCrossing
3493 << " v=" << v
3494 << " vSafeLeader=" << vsafeLeader
3495 << " vLinkPass=" << vLinkPass
3496 << "\n";
3497#endif
3498 }
3499}
3500
3501
3502void
3503MSVehicle::adaptToOncomingLeader(const std::pair<const MSVehicle*, double> leaderInfo,
3504 DriveProcessItem* const lastLink,
3505 double& v, double& vLinkPass) const {
3506 if (leaderInfo.first != 0) {
3507 if (ignoreFoe(leaderInfo.first)) {
3508#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3509 if (DEBUG_COND) {
3510 std::cout << " oncoming foe ignored\n";
3511 }
3512#endif
3513 return;
3514 }
3515 const MSCFModel& cfModel = getCarFollowModel();
3516 const MSVehicle* lead = leaderInfo.first;
3517 const MSCFModel& cfModelL = lead->getCarFollowModel();
3518 // assume the leader reacts symmetrically (neither stopping instantly nor ignoring ego)
3519 const double leaderBrakeGap = cfModelL.brakeGap(lead->getSpeed(), cfModelL.getMaxDecel(), 0);
3520 const double egoBrakeGap = cfModel.brakeGap(getSpeed(), cfModel.getMaxDecel(), 0);
3521 const double gapSum = leaderBrakeGap + egoBrakeGap;
3522 // ensure that both vehicles can leave an intersection if they are currently on it
3523 double egoExit = getDistanceToLeaveJunction();
3524 const double leaderExit = lead->getDistanceToLeaveJunction();
3525 double gap = leaderInfo.second;
3526 if (egoExit + leaderExit < gap) {
3527 gap -= egoExit + leaderExit;
3528 } else {
3529 egoExit = 0;
3530 }
3531 // split any distance in excess of brakeGaps evenly
3532 const double freeGap = MAX2(0.0, gap - gapSum);
3533 const double splitGap = MIN2(gap, gapSum);
3534 // assume remaining distance is allocated in proportion to braking distance
3535 const double gapRatio = gapSum > 0 ? egoBrakeGap / gapSum : 0.5;
3536 const double vsafeLeader = cfModel.stopSpeed(this, getSpeed(), splitGap * gapRatio + egoExit + 0.5 * freeGap);
3537 if (lastLink != nullptr) {
3538 const double futureVSafe = cfModel.stopSpeed(this, lastLink->accelV, leaderInfo.second, MSCFModel::CalcReason::FUTURE);
3539 lastLink->adaptLeaveSpeed(futureVSafe);
3540#ifdef DEBUG_PLAN_MOVE
3541 if (DEBUG_COND) {
3542 std::cout << " vlinkpass=" << lastLink->myVLinkPass << " futureVSafe=" << futureVSafe << "\n";
3543 }
3544#endif
3545 }
3546 v = MIN2(v, vsafeLeader);
3547 vLinkPass = MIN2(vLinkPass, vsafeLeader);
3548#ifdef DEBUG_PLAN_MOVE
3549 if (DEBUG_COND) std::cout
3550 << SIMTIME
3551 //std::cout << std::setprecision(10);
3552 << " veh=" << getID()
3553 << " oncomingLead=" << lead->getID()
3554 << " leadSpeed=" << lead->getSpeed()
3555 << " gap=" << leaderInfo.second
3556 << " gap2=" << gap
3557 << " gapRatio=" << gapRatio
3558 << " leadLane=" << lead->getLane()->getID()
3559 << " predPos=" << lead->getPositionOnLane()
3560 << " myLane=" << myLane->getID()
3561 << " v=" << v
3562 << " vSafeLeader=" << vsafeLeader
3563 << " vLinkPass=" << vLinkPass
3564 << "\n";
3565#endif
3566 }
3567}
3568
3569
3570void
3571MSVehicle::checkLinkLeaderCurrentAndParallel(const MSLink* link, const MSLane* lane, double seen,
3572 DriveProcessItem* const lastLink, double& v, double& vLinkPass, double& vLinkWait, bool& setRequest) const {
3574 // we want to pass the link but need to check for foes on internal lanes
3575 checkLinkLeader(link, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest);
3576 if (myLaneChangeModel->getShadowLane() != nullptr) {
3577 const MSLink* const parallelLink = link->getParallelLink(myLaneChangeModel->getShadowDirection());
3578 if (parallelLink != nullptr) {
3579 checkLinkLeader(parallelLink, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest, true);
3580 }
3581 }
3582 }
3583
3584}
3585
3586void
3587MSVehicle::checkLinkLeader(const MSLink* link, const MSLane* lane, double seen,
3588 DriveProcessItem* const lastLink, double& v, double& vLinkPass, double& vLinkWait, bool& setRequest,
3589 bool isShadowLink) const {
3590#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3591 if (DEBUG_COND) {
3592 gDebugFlag1 = true; // See MSLink::getLeaderInfo
3593 }
3594#endif
3595 const MSLink::LinkLeaders linkLeaders = link->getLeaderInfo(this, seen, nullptr, isShadowLink);
3596#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3597 if (DEBUG_COND) {
3598 gDebugFlag1 = false; // See MSLink::getLeaderInfo
3599 }
3600#endif
3601 for (MSLink::LinkLeaders::const_iterator it = linkLeaders.begin(); it != linkLeaders.end(); ++it) {
3602 // the vehicle to enter the junction first has priority
3603 const MSVehicle* leader = (*it).vehAndGap.first;
3604 if (leader == nullptr) {
3605 // leader is a pedestrian. Passing 'this' as a dummy.
3606#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3607 if (DEBUG_COND) {
3608 std::cout << SIMTIME << " veh=" << getID() << " is blocked on link to " << link->getViaLaneOrLane()->getID() << " by pedestrian. dist=" << it->distToCrossing << "\n";
3609 }
3610#endif
3613#ifdef DEBUG_PLAN_MOVE
3614 if (DEBUG_COND) {
3615 std::cout << SIMTIME << " veh=" << getID() << " is ignoring pedestrian (jmIgnoreJunctionFoeProb)\n";
3616 }
3617#endif
3618 continue;
3619 }
3620 adaptToJunctionLeader(std::make_pair(this, -1), seen, lastLink, lane, v, vLinkPass, it->distToCrossing);
3621 // if blocked by a pedestrian for too long we must yield our request
3623 setRequest = false;
3624#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3625 if (DEBUG_COND) {
3626 std::cout << " aborting request\n";
3627 }
3628#endif
3629 }
3630 } else if (isLeader(link, leader, (*it).vehAndGap.second) || (*it).inTheWay()) {
3633#ifdef DEBUG_PLAN_MOVE
3634 if (DEBUG_COND) {
3635 std::cout << SIMTIME << " veh=" << getID() << " is ignoring linkLeader=" << leader->getID() << " (jmIgnoreJunctionFoeProb)\n";
3636 }
3637#endif
3638 continue;
3639 }
3641 // sibling link (XXX: could also be partial occupator where this check fails)
3642 &leader->getLane()->getEdge() == &lane->getEdge()) {
3643 // check for sublane obstruction (trivial for sibling link leaders)
3644 const MSLane* conflictLane = link->getInternalLaneBefore();
3645 MSLeaderInfo linkLeadersAhead = MSLeaderInfo(conflictLane->getWidth());
3646 linkLeadersAhead.addLeader(leader, false, 0); // assume sibling lane has the same geometry as the leader lane
3647 const double latOffset = isShadowLink ? (getLane()->getRightSideOnEdge() - myLaneChangeModel->getShadowLane()->getRightSideOnEdge()) : 0;
3648 // leader is neither on lane nor conflictLane (the conflict is only established geometrically)
3649 adaptToLeaders(linkLeadersAhead, latOffset, seen, lastLink, leader->getLane(), v, vLinkPass);
3650#ifdef DEBUG_PLAN_MOVE
3651 if (DEBUG_COND) {
3652 std::cout << SIMTIME << " veh=" << getID()
3653 << " siblingFoe link=" << link->getViaLaneOrLane()->getID()
3654 << " isShadowLink=" << isShadowLink
3655 << " lane=" << lane->getID()
3656 << " foe=" << leader->getID()
3657 << " foeLane=" << leader->getLane()->getID()
3658 << " latOffset=" << latOffset
3659 << " latOffsetFoe=" << leader->getLatOffset(lane)
3660 << " linkLeadersAhead=" << linkLeadersAhead.toString()
3661 << "\n";
3662 }
3663#endif
3664 } else {
3665#ifdef DEBUG_PLAN_MOVE
3666 if (DEBUG_COND) {
3667 std::cout << SIMTIME << " veh=" << getID() << " linkLeader=" << leader->getID() << " gap=" << it->vehAndGap.second
3668 << " ET=" << myJunctionEntryTime << " lET=" << leader->myJunctionEntryTime
3669 << " ETN=" << myJunctionEntryTimeNeverYield << " lETN=" << leader->myJunctionEntryTimeNeverYield
3670 << " CET=" << myJunctionConflictEntryTime << " lCET=" << leader->myJunctionConflictEntryTime
3671 << "\n";
3672 }
3673#endif
3674 adaptToJunctionLeader(it->vehAndGap, seen, lastLink, lane, v, vLinkPass, it->distToCrossing);
3675 }
3676 if (lastLink != nullptr) {
3677 // we are not yet on the junction with this linkLeader.
3678 // at least we can drive up to the previous link and stop there
3679 v = MAX2(v, lastLink->myVLinkWait);
3680 }
3681 // if blocked by a leader from the same or next lane we must yield our request
3682 // also, if blocked by a stopped or blocked leader
3684 //&& leader->getSpeed() < SUMO_const_haltingSpeed
3686 || leader->getLane()->getLogicalPredecessorLane() == myLane
3687 || leader->isStopped()
3689 setRequest = false;
3690#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3691 if (DEBUG_COND) {
3692 std::cout << " aborting request\n";
3693 }
3694#endif
3695 if (lastLink != nullptr && leader->getLane()->getLogicalPredecessorLane() == myLane) {
3696 // we are not yet on the junction so must abort that request as well
3697 // (or maybe we are already on the junction and the leader is a partial occupator beyond)
3698 lastLink->mySetRequest = false;
3699#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3700 if (DEBUG_COND) {
3701 std::cout << " aborting previous request\n";
3702 }
3703#endif
3704 }
3705 }
3706 }
3707#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3708 else {
3709 if (DEBUG_COND) {
3710 std::cout << SIMTIME << " veh=" << getID() << " ignoring leader " << leader->getID() << " gap=" << (*it).vehAndGap.second << " dtC=" << (*it).distToCrossing
3711 << " ET=" << myJunctionEntryTime << " lET=" << leader->myJunctionEntryTime
3712 << " ETN=" << myJunctionEntryTimeNeverYield << " lETN=" << leader->myJunctionEntryTimeNeverYield
3713 << " CET=" << myJunctionConflictEntryTime << " lCET=" << leader->myJunctionConflictEntryTime
3714 << "\n";
3715 }
3716 }
3717#endif
3718 }
3719 // if this is the link between two internal lanes we may have to slow down for pedestrians
3720 vLinkWait = MIN2(vLinkWait, v);
3721}
3722
3723
3724double
3725MSVehicle::getDeltaPos(const double accel) const {
3726 double vNext = myState.mySpeed + ACCEL2SPEED(accel);
3728 // apply implicit Euler positional update
3729 return SPEED2DIST(MAX2(vNext, 0.));
3730 } else {
3731 // apply ballistic update
3732 if (vNext >= 0) {
3733 // assume constant acceleration during this time step
3734 return SPEED2DIST(myState.mySpeed + 0.5 * ACCEL2SPEED(accel));
3735 } else {
3736 // negative vNext indicates a stop within the middle of time step
3737 // The corresponding stop time is s = mySpeed/deceleration \in [0,dt], and the
3738 // covered distance is therefore deltaPos = mySpeed*s - 0.5*deceleration*s^2.
3739 // Here, deceleration = (myState.mySpeed - vNext)/dt is the constant deceleration
3740 // until the vehicle stops.
3741 return -SPEED2DIST(0.5 * myState.mySpeed * myState.mySpeed / ACCEL2SPEED(accel));
3742 }
3743 }
3744}
3745
3746void
3747MSVehicle::processLinkApproaches(double& vSafe, double& vSafeMin, double& vSafeMinDist) {
3748
3749 const MSCFModel& cfModel = getCarFollowModel();
3750 // Speed limit due to zipper merging
3751 double vSafeZipper = std::numeric_limits<double>::max();
3752
3753 myHaveToWaitOnNextLink = false;
3754 bool canBrakeVSafeMin = false;
3755
3756 // Get safe velocities from DriveProcessItems.
3757 assert(myLFLinkLanes.size() != 0 || isRemoteControlled());
3758 for (const DriveProcessItem& dpi : myLFLinkLanes) {
3759 MSLink* const link = dpi.myLink;
3760
3761#ifdef DEBUG_EXEC_MOVE
3762 if (DEBUG_COND) {
3763 std::cout
3764 << SIMTIME
3765 << " veh=" << getID()
3766 << " link=" << (link == 0 ? "NULL" : link->getViaLaneOrLane()->getID())
3767 << " req=" << dpi.mySetRequest
3768 << " vP=" << dpi.myVLinkPass
3769 << " vW=" << dpi.myVLinkWait
3770 << " d=" << dpi.myDistance
3771 << "\n";
3772 gDebugFlag1 = true; // See MSLink_DEBUG_OPENED
3773 }
3774#endif
3775
3776 // the vehicle must change the lane on one of the next lanes (XXX: refs to code further below???, Leo)
3777 if (link != nullptr && dpi.mySetRequest) {
3778
3779 const LinkState ls = link->getState();
3780 // vehicles should brake when running onto a yellow light if the distance allows to halt in front
3781 const bool yellow = link->haveYellow();
3782 const bool canBrake = (dpi.myDistance > cfModel.brakeGap(myState.mySpeed, cfModel.getMaxDecel(), 0.)
3784 assert(link->getLaneBefore() != nullptr);
3785 const bool beyondStopLine = dpi.myDistance < link->getLaneBefore()->getVehicleStopOffset(this);
3786 const bool ignoreRedLink = ignoreRed(link, canBrake) || beyondStopLine;
3787 if (yellow && canBrake && !ignoreRedLink) {
3788 vSafe = dpi.myVLinkWait;
3790#ifdef DEBUG_CHECKREWINDLINKLANES
3791 if (DEBUG_COND) {
3792 std::cout << SIMTIME << " veh=" << getID() << " haveToWait (yellow)\n";
3793 }
3794#endif
3795 break;
3796 }
3797 const bool influencerPrio = (myInfluencer != nullptr && !myInfluencer->getRespectJunctionPriority());
3798 MSLink::BlockingFoes collectFoes;
3799 bool opened = (yellow || influencerPrio
3800 || link->opened(dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
3802 canBrake ? getImpatience() : 1,
3803 cfModel.getMaxDecel(),
3805 ls == LINKSTATE_ZIPPER ? &collectFoes : nullptr,
3806 ignoreRedLink, this, dpi.myDistance));
3807 if (opened && myLaneChangeModel->getShadowLane() != nullptr) {
3808 const MSLink* const parallelLink = dpi.myLink->getParallelLink(myLaneChangeModel->getShadowDirection());
3809 if (parallelLink != nullptr) {
3810 const double shadowLatPos = getLateralPositionOnLane() - myLaneChangeModel->getShadowDirection() * 0.5 * (
3812 opened = yellow || influencerPrio || (opened && parallelLink->opened(dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
3814 canBrake ? getImpatience() : 1,
3815 cfModel.getMaxDecel(),
3816 getWaitingTimeFor(link), shadowLatPos, nullptr,
3817 ignoreRedLink, this, dpi.myDistance));
3818#ifdef DEBUG_EXEC_MOVE
3819 if (DEBUG_COND) {
3820 std::cout << SIMTIME
3821 << " veh=" << getID()
3822 << " shadowLane=" << myLaneChangeModel->getShadowLane()->getID()
3823 << " shadowDir=" << myLaneChangeModel->getShadowDirection()
3824 << " parallelLink=" << (parallelLink == 0 ? "NULL" : parallelLink->getViaLaneOrLane()->getID())
3825 << " opened=" << opened
3826 << "\n";
3827 }
3828#endif
3829 }
3830 }
3831 // vehicles should decelerate when approaching a minor link
3832#ifdef DEBUG_EXEC_MOVE
3833 if (DEBUG_COND) {
3834 std::cout << SIMTIME
3835 << " opened=" << opened
3836 << " influencerPrio=" << influencerPrio
3837 << " linkPrio=" << link->havePriority()
3838 << " lastContMajor=" << link->lastWasContMajor()
3839 << " isCont=" << link->isCont()
3840 << " ignoreRed=" << ignoreRedLink
3841 << " canBrake=" << canBrake
3842 << "\n";
3843 }
3844#endif
3845 double visibilityDistance = link->getFoeVisibilityDistance();
3846 bool determinedFoePresence = dpi.myDistance <= visibilityDistance;
3847 if (opened && !influencerPrio && !link->havePriority() && !link->lastWasContMajor() && !link->isCont() && !ignoreRedLink) {
3848 if (!determinedFoePresence && (canBrake || !yellow)) {
3849 vSafe = dpi.myVLinkWait;
3851#ifdef DEBUG_CHECKREWINDLINKLANES
3852 if (DEBUG_COND) {
3853 std::cout << SIMTIME << " veh=" << getID() << " haveToWait (minor)\n";
3854 }
3855#endif
3856 break;
3857 } else {
3858 // past the point of no return. we need to drive fast enough
3859 // to make it across the link. However, minor slowdowns
3860 // should be permissible to follow leading traffic safely
3861 // basically, this code prevents dawdling
3862 // (it's harder to do this later using
3863 // SUMO_ATTR_JM_SIGMA_MINOR because we don't know whether the
3864 // vehicle is already too close to stop at that part of the code)
3865 //
3866 // XXX: There is a problem in subsecond simulation: If we cannot
3867 // make it across the minor link in one step, new traffic
3868 // could appear on a major foe link and cause a collision. Refs. #1845, #2123
3869 vSafeMinDist = dpi.myDistance; // distance that must be covered
3871 vSafeMin = MIN3((double)DIST2SPEED(vSafeMinDist + POSITION_EPS), dpi.myVLinkPass, cfModel.maxNextSafeMin(getSpeed(), this));
3872 } else {
3873 vSafeMin = MIN3((double)DIST2SPEED(2 * vSafeMinDist + NUMERICAL_EPS) - getSpeed(), dpi.myVLinkPass, cfModel.maxNextSafeMin(getSpeed(), this));
3874 }
3875 canBrakeVSafeMin = canBrake;
3876#ifdef DEBUG_EXEC_MOVE
3877 if (DEBUG_COND) {
3878 std::cout << " vSafeMin=" << vSafeMin << " vSafeMinDist=" << vSafeMinDist << " canBrake=" << canBrake << "\n";
3879 }
3880#endif
3881 }
3882 }
3883 // have waited; may pass if opened...
3884 if (opened) {
3885 vSafe = dpi.myVLinkPass;
3886 if (vSafe < cfModel.getMaxDecel() && vSafe <= dpi.myVLinkWait && vSafe < cfModel.maxNextSpeed(getSpeed(), this)) {
3887 // this vehicle is probably not gonna drive across the next junction (heuristic)
3889#ifdef DEBUG_CHECKREWINDLINKLANES
3890 if (DEBUG_COND) {
3891 std::cout << SIMTIME << " veh=" << getID() << " haveToWait (very slow)\n";
3892 }
3893#endif
3894 }
3895 if (link->mustStop() && determinedFoePresence && myHaveStoppedFor == nullptr) {
3896 myHaveStoppedFor = link;
3897 }
3898 } else if (link->getState() == LINKSTATE_ZIPPER) {
3899 vSafeZipper = MIN2(vSafeZipper,
3900 link->getZipperSpeed(this, dpi.myDistance, dpi.myVLinkPass, dpi.myArrivalTime, &collectFoes));
3901 } else if (!canBrake
3902 // always brake hard for traffic lights (since an emergency stop is necessary anyway)
3903 && link->getTLLogic() == nullptr
3904 // cannot brake even with emergency deceleration
3905 && dpi.myDistance < cfModel.brakeGap(myState.mySpeed, cfModel.getEmergencyDecel(), 0.)) {
3906#ifdef DEBUG_EXEC_MOVE
3907 if (DEBUG_COND) {
3908 std::cout << SIMTIME << " too fast to brake for closed link\n";
3909 }
3910#endif
3911 vSafe = dpi.myVLinkPass;
3912 } else {
3913 vSafe = dpi.myVLinkWait;
3915#ifdef DEBUG_CHECKREWINDLINKLANES
3916 if (DEBUG_COND) {
3917 std::cout << SIMTIME << " veh=" << getID() << " haveToWait (closed)\n";
3918 }
3919#endif
3920#ifdef DEBUG_EXEC_MOVE
3921 if (DEBUG_COND) {
3922 std::cout << SIMTIME << " braking for closed link=" << link->getViaLaneOrLane()->getID() << "\n";
3923 }
3924#endif
3925 break;
3926 }
3928 // request was renewed, restoring entry time
3929 // @note: using myJunctionEntryTimeNeverYield could lead to inconsistencies with other vehicles already on the junction
3931 }
3932 } else {
3933 if (link != nullptr && link->getInternalLaneBefore() != nullptr && myLane->isInternal() && link->getJunction() == myLane->getEdge().getToJunction()) {
3934 // blocked on the junction. yield request so other vehicles may
3935 // become junction leader
3936#ifdef DEBUG_EXEC_MOVE
3937 if (DEBUG_COND) {
3938 std::cout << SIMTIME << " resetting junctionEntryTime at junction '" << link->getJunction()->getID() << "' beause of non-request exitLink\n";
3939 }
3940#endif
3943 }
3944 // we have: i->link == 0 || !i->setRequest
3945 vSafe = dpi.myVLinkWait;
3946 if (link != nullptr || myStopDist < (myLane->getLength() - getPositionOnLane())) {
3947 if (vSafe < getSpeed()) {
3949#ifdef DEBUG_CHECKREWINDLINKLANES
3950 if (DEBUG_COND) {
3951 std::cout << SIMTIME << " veh=" << getID() << " haveToWait (no request, braking) vSafe=" << vSafe << "\n";
3952 }
3953#endif
3954 } else if (vSafe < SUMO_const_haltingSpeed) {
3956#ifdef DEBUG_CHECKREWINDLINKLANES
3957 if (DEBUG_COND) {
3958 std::cout << SIMTIME << " veh=" << getID() << " haveToWait (no request, stopping)\n";
3959 }
3960#endif
3961 }
3962 }
3963 if (link == nullptr && myLFLinkLanes.size() == 1
3964 && getBestLanesContinuation().size() > 1
3965 && getBestLanesContinuation()[1]->hadPermissionChanges()
3966 && myLane->getFirstAnyVehicle() == this) {
3967 // temporal lane closing without notification, visible to the
3968 // vehicle at the front of the queue
3969 updateBestLanes(true);
3970 //std::cout << SIMTIME << " veh=" << getID() << " updated bestLanes=" << toString(getBestLanesContinuation()) << "\n";
3971 }
3972 break;
3973 }
3974 }
3975
3976//#ifdef DEBUG_EXEC_MOVE
3977// if (DEBUG_COND) {
3978// std::cout << "\nvCurrent = " << toString(getSpeed(), 24) << "" << std::endl;
3979// std::cout << "vSafe = " << toString(vSafe, 24) << "" << std::endl;
3980// std::cout << "vSafeMin = " << toString(vSafeMin, 24) << "" << std::endl;
3981// std::cout << "vSafeMinDist = " << toString(vSafeMinDist, 24) << "" << std::endl;
3982//
3983// double gap = getLeader().second;
3984// std::cout << "gap = " << toString(gap, 24) << std::endl;
3985// std::cout << "vSafeStoppedLeader = " << toString(getCarFollowModel().stopSpeed(this, getSpeed(), gap, MSCFModel::CalcReason::FUTURE), 24)
3986// << "\n" << std::endl;
3987// }
3988//#endif
3989
3990 if ((MSGlobals::gSemiImplicitEulerUpdate && vSafe + NUMERICAL_EPS < vSafeMin)
3991 || (!MSGlobals::gSemiImplicitEulerUpdate && (vSafe + NUMERICAL_EPS < vSafeMin && vSafeMin != 0))) { // this might be good for the euler case as well
3992 // XXX: (Leo) This often called stopSpeed with vSafeMinDist==0 (for the ballistic update), since vSafe can become negative
3993 // For the Euler update the term '+ NUMERICAL_EPS' prevented a call here... Recheck, consider of -INVALID_SPEED instead of 0 to indicate absence of vSafeMin restrictions. Refs. #2577
3994#ifdef DEBUG_EXEC_MOVE
3995 if (DEBUG_COND) {
3996 std::cout << "vSafeMin Problem? vSafe=" << vSafe << " vSafeMin=" << vSafeMin << " vSafeMinDist=" << vSafeMinDist << std::endl;
3997 }
3998#endif
3999 if (canBrakeVSafeMin && vSafe < getSpeed()) {
4000 // cannot drive across a link so we need to stop before it
4001 vSafe = MIN2(vSafe, MAX2(getCarFollowModel().minNextSpeed(getSpeed(), this),
4002 getCarFollowModel().stopSpeed(this, getSpeed(), vSafeMinDist)));
4003 vSafeMin = 0;
4005#ifdef DEBUG_CHECKREWINDLINKLANES
4006 if (DEBUG_COND) {
4007 std::cout << SIMTIME << " veh=" << getID() << " haveToWait (vSafe=" << vSafe << " < vSafeMin=" << vSafeMin << ")\n";
4008 }
4009#endif
4010 } else {
4011 // if the link is yellow or visibility distance is large
4012 // then we might not make it across the link in one step anyway..
4013 // Possibly, the lane after the intersection has a lower speed limit so
4014 // we really need to drive slower already
4015 // -> keep driving without dawdling
4016 vSafeMin = vSafe;
4017 }
4018 }
4019
4020 // vehicles inside a roundabout should maintain their requests
4021 if (myLane->getEdge().isRoundabout()) {
4022 myHaveToWaitOnNextLink = false;
4023 }
4024
4025 vSafe = MIN2(vSafe, vSafeZipper);
4026}
4027
4028
4029double
4030MSVehicle::processTraCISpeedControl(double vSafe, double vNext) {
4031 if (myInfluencer != nullptr) {
4033#ifdef DEBUG_TRACI
4034 if DEBUG_COND2(this) {
4035 std::cout << SIMTIME << " MSVehicle::processTraCISpeedControl() for vehicle '" << getID() << "'"
4036 << " vSafe=" << vSafe << " (init)vNext=" << vNext << " keepStopping=" << keepStopping();
4037 }
4038#endif
4041 }
4042 const double vMax = getVehicleType().getCarFollowModel().maxNextSpeed(myState.mySpeed, this);
4045 vMin = MAX2(0., vMin);
4046 }
4047 vNext = myInfluencer->influenceSpeed(MSNet::getInstance()->getCurrentTimeStep(), vNext, vSafe, vMin, vMax);
4048 if (keepStopping() && myStops.front().getSpeed() == 0) {
4049 // avoid driving while stopped (unless it's actually a waypoint
4050 vNext = myInfluencer->getOriginalSpeed();
4051 }
4052#ifdef DEBUG_TRACI
4053 if DEBUG_COND2(this) {
4054 std::cout << " (processed)vNext=" << vNext << std::endl;
4055 }
4056#endif
4057 }
4058 return vNext;
4059}
4060
4061
4062void
4064#ifdef DEBUG_ACTIONSTEPS
4065 if (DEBUG_COND) {
4066 std::cout << SIMTIME << " veh=" << getID() << " removePassedDriveItems()\n"
4067 << " Current items: ";
4068 for (auto& j : myLFLinkLanes) {
4069 if (j.myLink == 0) {
4070 std::cout << "\n Stop at distance " << j.myDistance;
4071 } else {
4072 const MSLane* to = j.myLink->getViaLaneOrLane();
4073 const MSLane* from = j.myLink->getLaneBefore();
4074 std::cout << "\n Link at distance " << j.myDistance << ": '"
4075 << (from == 0 ? "NONE" : from->getID()) << "' -> '" << (to == 0 ? "NONE" : to->getID()) << "'";
4076 }
4077 }
4078 std::cout << "\n myNextDriveItem: ";
4079 if (myLFLinkLanes.size() != 0) {
4080 if (myNextDriveItem->myLink == 0) {
4081 std::cout << "\n Stop at distance " << myNextDriveItem->myDistance;
4082 } else {
4083 const MSLane* to = myNextDriveItem->myLink->getViaLaneOrLane();
4084 const MSLane* from = myNextDriveItem->myLink->getLaneBefore();
4085 std::cout << "\n Link at distance " << myNextDriveItem->myDistance << ": '"
4086 << (from == 0 ? "NONE" : from->getID()) << "' -> '" << (to == 0 ? "NONE" : to->getID()) << "'";
4087 }
4088 }
4089 std::cout << std::endl;
4090 }
4091#endif
4092 for (auto j = myLFLinkLanes.begin(); j != myNextDriveItem; ++j) {
4093#ifdef DEBUG_ACTIONSTEPS
4094 if (DEBUG_COND) {
4095 std::cout << " Removing item: ";
4096 if (j->myLink == 0) {
4097 std::cout << "Stop at distance " << j->myDistance;
4098 } else {
4099 const MSLane* to = j->myLink->getViaLaneOrLane();
4100 const MSLane* from = j->myLink->getLaneBefore();
4101 std::cout << "Link at distance " << j->myDistance << ": '"
4102 << (from == 0 ? "NONE" : from->getID()) << "' -> '" << (to == 0 ? "NONE" : to->getID()) << "'";
4103 }
4104 std::cout << std::endl;
4105 }
4106#endif
4107 if (j->myLink != nullptr) {
4108 j->myLink->removeApproaching(this);
4109 }
4110 }
4113}
4114
4115
4116void
4118#ifdef DEBUG_ACTIONSTEPS
4119 if (DEBUG_COND) {
4120 std::cout << SIMTIME << " updateDriveItems(), veh='" << getID() << "' (lane: '" << getLane()->getID() << "')\nCurrent drive items:" << std::endl;
4121 for (const auto& dpi : myLFLinkLanes) {
4122 std::cout
4123 << " vPass=" << dpi.myVLinkPass
4124 << " vWait=" << dpi.myVLinkWait
4125 << " linkLane=" << (dpi.myLink == 0 ? "NULL" : dpi.myLink->getViaLaneOrLane()->getID())
4126 << " request=" << dpi.mySetRequest
4127 << "\n";
4128 }
4129 std::cout << " myNextDriveItem's linked lane: " << (myNextDriveItem->myLink == 0 ? "NULL" : myNextDriveItem->myLink->getViaLaneOrLane()->getID()) << std::endl;
4130 }
4131#endif
4132 if (myLFLinkLanes.size() == 0) {
4133 // nothing to update
4134 return;
4135 }
4136 const MSLink* nextPlannedLink = nullptr;
4137// auto i = myLFLinkLanes.begin();
4138 auto i = myNextDriveItem;
4139 while (i != myLFLinkLanes.end() && nextPlannedLink == nullptr) {
4140 nextPlannedLink = i->myLink;
4141 ++i;
4142 }
4143
4144 if (nextPlannedLink == nullptr) {
4145 // No link for upcoming item -> no need for an update
4146#ifdef DEBUG_ACTIONSTEPS
4147 if (DEBUG_COND) {
4148 std::cout << "Found no link-related drive item." << std::endl;
4149 }
4150#endif
4151 return;
4152 }
4153
4154 if (getLane() == nextPlannedLink->getLaneBefore()) {
4155 // Current lane approaches the stored next link, i.e. no LC happend and no update is required.
4156#ifdef DEBUG_ACTIONSTEPS
4157 if (DEBUG_COND) {
4158 std::cout << "Continuing on planned lane sequence, no update required." << std::endl;
4159 }
4160#endif
4161 return;
4162 }
4163 // Lane must have been changed, determine the change direction
4164 const MSLink* parallelLink = nextPlannedLink->getParallelLink(1);
4165 if (parallelLink != nullptr && parallelLink->getLaneBefore() == getLane()) {
4166 // lcDir = 1;
4167 } else {
4168 parallelLink = nextPlannedLink->getParallelLink(-1);
4169 if (parallelLink != nullptr && parallelLink->getLaneBefore() == getLane()) {
4170 // lcDir = -1;
4171 } else {
4172 // If the vehicle's current lane is not the approaching lane for the next
4173 // drive process item's link, it is expected to lead to a parallel link,
4174 // XXX: What if the lc was an overtaking maneuver and there is no upcoming link?
4175 // Then a stop item should be scheduled! -> TODO!
4176 //assert(false);
4177 return;
4178 }
4179 }
4180#ifdef DEBUG_ACTIONSTEPS
4181 if (DEBUG_COND) {
4182 std::cout << "Changed lane. Drive items will be updated along the current lane continuation." << std::endl;
4183 }
4184#endif
4185 // Trace link sequence along current best lanes and transfer drive items to the corresponding links
4186// DriveItemVector::iterator driveItemIt = myLFLinkLanes.begin();
4187 DriveItemVector::iterator driveItemIt = myNextDriveItem;
4188 // In the loop below, lane holds the currently considered lane on the vehicles continuation (including internal lanes)
4189 const MSLane* lane = myLane;
4190 assert(myLane == parallelLink->getLaneBefore());
4191 // *lit is a pointer to the next lane in best continuations for the current lane (always non-internal)
4192 std::vector<MSLane*>::const_iterator bestLaneIt = getBestLanesContinuation().begin() + 1;
4193 // Pointer to the new link for the current drive process item
4194 MSLink* newLink = nullptr;
4195 while (driveItemIt != myLFLinkLanes.end()) {
4196 if (driveItemIt->myLink == nullptr) {
4197 // Items not related to a specific link are not updated
4198 // (XXX: when a stop item corresponded to a dead end, which is overcome by the LC that made
4199 // the update necessary, this may slow down the vehicle's continuation on the new lane...)
4200 ++driveItemIt;
4201 continue;
4202 }
4203 // Continuation links for current best lanes are less than for the former drive items (myLFLinkLanes)
4204 // We just remove the leftover link-items, as they cannot be mapped to new links.
4205 if (bestLaneIt == getBestLanesContinuation().end()) {
4206#ifdef DEBUG_ACTIONSTEPS
4207 if (DEBUG_COND) {
4208 std::cout << "Reached end of the new continuation sequence. Erasing leftover link-items." << std::endl;
4209 }
4210#endif
4211 while (driveItemIt != myLFLinkLanes.end()) {
4212 if (driveItemIt->myLink == nullptr) {
4213 ++driveItemIt;
4214 continue;
4215 } else {
4216 driveItemIt->myLink->removeApproaching(this);
4217 driveItemIt = myLFLinkLanes.erase(driveItemIt);
4218 }
4219 }
4220 break;
4221 }
4222 // Do the actual link-remapping for the item. And un/register approaching information on the corresponding links
4223 const MSLane* const target = *bestLaneIt;
4224 assert(!target->isInternal());
4225 newLink = nullptr;
4226 for (MSLink* const link : lane->getLinkCont()) {
4227 if (link->getLane() == target) {
4228 newLink = link;
4229 break;
4230 }
4231 }
4232
4233 if (newLink == driveItemIt->myLink) {
4234 // new continuation merged into previous - stop update
4235#ifdef DEBUG_ACTIONSTEPS
4236 if (DEBUG_COND) {
4237 std::cout << "Old and new continuation sequences merge at link\n"
4238 << "'" << newLink->getLaneBefore()->getID() << "'->'" << newLink->getViaLaneOrLane()->getID() << "'"
4239 << "\nNo update beyond merge required." << std::endl;
4240 }
4241#endif
4242 break;
4243 }
4244
4245#ifdef DEBUG_ACTIONSTEPS
4246 if (DEBUG_COND) {
4247 std::cout << "lane=" << lane->getID() << "\nUpdating link\n '" << driveItemIt->myLink->getLaneBefore()->getID() << "'->'" << driveItemIt->myLink->getViaLaneOrLane()->getID() << "'"
4248 << "==> " << "'" << newLink->getLaneBefore()->getID() << "'->'" << newLink->getViaLaneOrLane()->getID() << "'" << std::endl;
4249 }
4250#endif
4251 newLink->setApproaching(this, driveItemIt->myLink->getApproaching(this));
4252 driveItemIt->myLink->removeApproaching(this);
4253 driveItemIt->myLink = newLink;
4254 lane = newLink->getViaLaneOrLane();
4255 ++driveItemIt;
4256 if (!lane->isInternal()) {
4257 ++bestLaneIt;
4258 }
4259 }
4260#ifdef DEBUG_ACTIONSTEPS
4261 if (DEBUG_COND) {
4262 std::cout << "Updated drive items:" << std::endl;
4263 for (const auto& dpi : myLFLinkLanes) {
4264 std::cout
4265 << " vPass=" << dpi.myVLinkPass
4266 << " vWait=" << dpi.myVLinkWait
4267 << " linkLane=" << (dpi.myLink == 0 ? "NULL" : dpi.myLink->getViaLaneOrLane()->getID())
4268 << " request=" << dpi.mySetRequest
4269 << "\n";
4270 }
4271 }
4272#endif
4273}
4274
4275
4276void
4278 // To avoid casual blinking brake lights at high speeds due to dawdling of the
4279 // leading vehicle, we don't show brake lights when the deceleration could be caused
4280 // by frictional forces and air resistance (i.e. proportional to v^2, coefficient could be adapted further)
4281 double pseudoFriction = (0.05 + 0.005 * getSpeed()) * getSpeed();
4282 bool brakelightsOn = vNext < getSpeed() - ACCEL2SPEED(pseudoFriction);
4283
4284 if (vNext <= SUMO_const_haltingSpeed) {
4285 brakelightsOn = true;
4286 }
4287 if (brakelightsOn && !isStopped()) {
4289 } else {
4291 }
4292}
4293
4294
4295void
4300 } else {
4301 myWaitingTime = 0;
4303 if (hasInfluencer()) {
4305 }
4306 }
4307}
4308
4309
4310void
4312 // update time loss (depends on the updated edge)
4313 if (!isStopped()) {
4314 // some cfModels (i.e. EIDM may drive faster than predicted by maxNextSpeed)
4315 const double vmax = MIN2(myLane->getVehicleMaxSpeed(this), MAX2(myStopSpeed, vNext));
4316 if (vmax > 0) {
4317 myTimeLoss += TS * (vmax - vNext) / vmax;
4318 }
4319 }
4320}
4321
4322
4323double
4324MSVehicle::checkReversal(bool& canReverse, double speedThreshold, double seen) const {
4325 const bool stopOk = (myStops.empty() || myStops.front().edge != myCurrEdge
4326 || (myStops.front().getSpeed() > 0 && myState.myPos > myStops.front().pars.endPos - 2 * POSITION_EPS));
4327#ifdef DEBUG_REVERSE_BIDI
4328 if (DEBUG_COND) std::cout << SIMTIME << " checkReversal lane=" << myLane->getID()
4329 << " pos=" << myState.myPos
4330 << " speed=" << std::setprecision(6) << getPreviousSpeed() << std::setprecision(gPrecision)
4331 << " speedThreshold=" << speedThreshold
4332 << " seen=" << seen
4333 << " isRail=" << isRail()
4334 << " speedOk=" << (getPreviousSpeed() <= speedThreshold)
4335 << " posOK=" << (myState.myPos <= myLane->getLength())
4336 << " normal=" << !myLane->isInternal()
4337 << " routeOK=" << ((myCurrEdge + 1) != myRoute->end())
4338 << " bidi=" << (myLane->getEdge().getBidiEdge() == *(myCurrEdge + 1))
4339 << " stopOk=" << stopOk
4340 << "\n";
4341#endif
4342 if ((getVClass() & SVC_RAIL_CLASSES) != 0
4343 && getPreviousSpeed() <= speedThreshold
4344 && myState.myPos <= myLane->getLength()
4345 && !myLane->isInternal()
4346 && (myCurrEdge + 1) != myRoute->end()
4347 && myLane->getEdge().getBidiEdge() == *(myCurrEdge + 1)
4348 // ensure there are no further stops on this edge
4349 && stopOk
4350 ) {
4351 //if (isSelected()) std::cout << " check1 passed\n";
4352
4353 // ensure that the vehicle is fully on bidi edges that allow reversal
4354 const int neededFutureRoute = 1 + (int)(MSGlobals::gUsingInternalLanes && MSNet::getInstance()->hasInternalLinks()
4355 ? ceil((double)myFurtherLanes.size() / 2.0)
4356 : myFurtherLanes.size());
4357 const int remainingRoute = int(myRoute->end() - myCurrEdge) - 1;
4358 if (remainingRoute < neededFutureRoute) {
4359#ifdef DEBUG_REVERSE_BIDI
4360 if (DEBUG_COND) {
4361 std::cout << " fail: remainingEdges=" << ((int)(myRoute->end() - myCurrEdge)) << " further=" << myFurtherLanes.size() << "\n";
4362 }
4363#endif
4364 return getMaxSpeed();
4365 }
4366 //if (isSelected()) std::cout << " check2 passed\n";
4367
4368 // ensure that the turn-around connection exists from the current edge to its bidi-edge
4369 const MSEdgeVector& succ = myLane->getEdge().getSuccessors();
4370 if (std::find(succ.begin(), succ.end(), myLane->getEdge().getBidiEdge()) == succ.end()) {
4371#ifdef DEBUG_REVERSE_BIDI
4372 if (DEBUG_COND) {
4373 std::cout << " noTurn (bidi=" << myLane->getEdge().getBidiEdge()->getID() << " succ=" << toString(succ) << "\n";
4374 }
4375#endif
4376 return getMaxSpeed();
4377 }
4378 //if (isSelected()) std::cout << " check3 passed\n";
4379
4380 // ensure that the vehicle front will not move past a stop on the bidi edge of the current edge
4381 if (!myStops.empty() && myStops.front().edge == (myCurrEdge + 1)) {
4382 const double stopPos = myStops.front().getEndPos(*this);
4383 const double brakeDist = getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), 0);
4384 const double newPos = myLane->getLength() - (getBackPositionOnLane() + brakeDist);
4385 if (newPos > stopPos) {
4386#ifdef DEBUG_REVERSE_BIDI
4387 if (DEBUG_COND) {
4388 std::cout << " reversal would go past stop on " << myLane->getBidiLane()->getID() << "\n";
4389 }
4390#endif
4391 if (seen > MAX2(brakeDist, 1.0)) {
4392 return getMaxSpeed();
4393 } else {
4394#ifdef DEBUG_REVERSE_BIDI
4395 if (DEBUG_COND) {
4396 std::cout << " train is too long, skipping stop at " << stopPos << " cannot be avoided\n";
4397 }
4398#endif
4399 }
4400 }
4401 }
4402 //if (isSelected()) std::cout << " check4 passed\n";
4403
4404 // ensure that bidi-edges exist for all further edges
4405 // and that no stops will be skipped when reversing
4406 // and that the train will not be on top of a red rail signal after reversal
4407 const MSLane* bidi = myLane->getBidiLane();
4408 int view = 2;
4409 for (MSLane* further : myFurtherLanes) {
4410 if (!further->getEdge().isInternal()) {
4411 if (further->getEdge().getBidiEdge() != *(myCurrEdge + view)) {
4412#ifdef DEBUG_REVERSE_BIDI
4413 if (DEBUG_COND) {
4414 std::cout << " noBidi view=" << view << " further=" << further->getID() << " furtherBidi=" << Named::getIDSecure(further->getEdge().getBidiEdge()) << " future=" << (*(myCurrEdge + view))->getID() << "\n";
4415 }
4416#endif
4417 return getMaxSpeed();
4418 }
4419 const MSLane* nextBidi = further->getBidiLane();
4420 const MSLink* toNext = bidi->getLinkTo(nextBidi);
4421 if (toNext == nullptr) {
4422 // can only happen if the route is invalid
4423 return getMaxSpeed();
4424 }
4425 if (toNext->haveRed()) {
4426#ifdef DEBUG_REVERSE_BIDI
4427 if (DEBUG_COND) {
4428 std::cout << " do not reverse on a red signal\n";
4429 }
4430#endif
4431 return getMaxSpeed();
4432 }
4433 bidi = nextBidi;
4434 if (!myStops.empty() && myStops.front().edge == (myCurrEdge + view)) {
4435 const double brakeDist = getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), 0);
4436 const double stopPos = myStops.front().getEndPos(*this);
4437 const double newPos = further->getLength() - (getBackPositionOnLane(further) + brakeDist);
4438 if (newPos > stopPos) {
4439#ifdef DEBUG_REVERSE_BIDI
4440 if (DEBUG_COND) {
4441 std::cout << " reversal would go past stop on further-opposite lane " << further->getBidiLane()->getID() << "\n";
4442 }
4443#endif
4444 if (seen > MAX2(brakeDist, 1.0)) {
4445 canReverse = false;
4446 return getMaxSpeed();
4447 } else {
4448#ifdef DEBUG_REVERSE_BIDI
4449 if (DEBUG_COND) {
4450 std::cout << " train is too long, skipping stop at " << stopPos << " cannot be avoided\n";
4451 }
4452#endif
4453 }
4454 }
4455 }
4456 view++;
4457 }
4458 }
4459 // reverse as soon as comfortably possible
4460 const double vMinComfortable = getCarFollowModel().minNextSpeed(getSpeed(), this);
4461#ifdef DEBUG_REVERSE_BIDI
4462 if (DEBUG_COND) {
4463 std::cout << SIMTIME << " seen=" << seen << " vReverseOK=" << vMinComfortable << "\n";
4464 }
4465#endif
4466 canReverse = true;
4467 return vMinComfortable;
4468 }
4469 return getMaxSpeed();
4470}
4471
4472
4473void
4474MSVehicle::processLaneAdvances(std::vector<MSLane*>& passedLanes, std::string& emergencyReason) {
4475 for (std::vector<MSLane*>::reverse_iterator i = myFurtherLanes.rbegin(); i != myFurtherLanes.rend(); ++i) {
4476 passedLanes.push_back(*i);
4477 }
4478 if (passedLanes.size() == 0 || passedLanes.back() != myLane) {
4479 passedLanes.push_back(myLane);
4480 }
4481 // let trains reverse direction
4482 bool reverseTrain = false;
4483 checkReversal(reverseTrain);
4484 if (reverseTrain) {
4485 // Train is 'reversing' so toggle the logical state
4487 // add some slack to ensure that the back of train does appear looped
4488 myState.myPos += 2 * (myLane->getLength() - myState.myPos) + myType->getLength() + NUMERICAL_EPS;
4489 myState.mySpeed = 0;
4490#ifdef DEBUG_REVERSE_BIDI
4491 if (DEBUG_COND) {
4492 std::cout << SIMTIME << " reversing train=" << getID() << " newPos=" << myState.myPos << "\n";
4493 }
4494#endif
4495 }
4496 // move on lane(s)
4497 if (myState.myPos > myLane->getLength()) {
4498 // The vehicle has moved at least to the next lane (maybe it passed even more than one)
4499 if (myCurrEdge != myRoute->end() - 1) {
4500 MSLane* approachedLane = myLane;
4501 // move the vehicle forward
4503 while (myNextDriveItem != myLFLinkLanes.end() && approachedLane != nullptr && myState.myPos > approachedLane->getLength()) {
4504 const MSLink* link = myNextDriveItem->myLink;
4505 const double linkDist = myNextDriveItem->myDistance;
4507 // check whether the vehicle was allowed to enter lane
4508 // otherwise it is decelerated and we do not need to test for it's
4509 // approach on the following lanes when a lane changing is performed
4510 // proceed to the next lane
4511 if (approachedLane->mustCheckJunctionCollisions()) {
4512 // vehicle moves past approachedLane within a single step, collision checking must still be done
4514 }
4515 if (link != nullptr) {
4516 if ((getVClass() & SVC_RAIL_CLASSES) != 0
4517 && !myLane->isInternal()
4518 && myLane->getBidiLane() != nullptr
4519 && link->getLane()->getBidiLane() == myLane
4520 && !reverseTrain) {
4521 emergencyReason = " because it must reverse direction";
4522 approachedLane = nullptr;
4523 break;
4524 }
4525 if ((getVClass() & SVC_RAIL_CLASSES) != 0
4526 && myState.myPos < myLane->getLength() + NUMERICAL_EPS
4527 && hasStops() && getNextStop().edge == myCurrEdge) {
4528 // avoid skipping stop due to numerical instability
4529 // this is a special case for rail vehicles because they
4530 // continue myLFLinkLanes past stops
4531 approachedLane = myLane;
4533 break;
4534 }
4535 approachedLane = link->getViaLaneOrLane();
4537 bool beyondStopLine = linkDist < link->getLaneBefore()->getVehicleStopOffset(this);
4538 if (link->haveRed() && !ignoreRed(link, false) && !beyondStopLine && !reverseTrain) {
4539 emergencyReason = " because of a red traffic light";
4540 break;
4541 }
4542 }
4543 if (reverseTrain && approachedLane->isInternal()) {
4544 // avoid getting stuck on a slow turn-around internal lane
4545 myState.myPos += approachedLane->getLength();
4546 }
4547 } else if (myState.myPos < myLane->getLength() + NUMERICAL_EPS) {
4548 // avoid warning due to numerical instability
4549 approachedLane = myLane;
4551 } else if (reverseTrain) {
4552 approachedLane = (*(myCurrEdge + 1))->getLanes()[0];
4553 link = myLane->getLinkTo(approachedLane);
4554 assert(link != 0);
4555 while (link->getViaLane() != nullptr) {
4556 link = link->getViaLane()->getLinkCont()[0];
4557 }
4559 } else {
4560 emergencyReason = " because there is no connection to the next edge";
4561 approachedLane = nullptr;
4562 break;
4563 }
4564 if (approachedLane != myLane && approachedLane != nullptr) {
4567 assert(myState.myPos > 0);
4568 enterLaneAtMove(approachedLane);
4569 if (link->isEntryLink()) {
4572 myHaveStoppedFor = nullptr;
4573 }
4574 if (link->isConflictEntryLink()) {
4576 // renew yielded request
4578 }
4579 if (link->isExitLink()) {
4580 // passed junction, reset for approaching the next one
4584 }
4585#ifdef DEBUG_PLAN_MOVE_LEADERINFO
4586 if (DEBUG_COND) {
4587 std::cout << "Update junctionTimes link=" << link->getViaLaneOrLane()->getID()
4588 << " entry=" << link->isEntryLink() << " conflict=" << link->isConflictEntryLink() << " exit=" << link->isExitLink()
4589 << " ET=" << myJunctionEntryTime
4590 << " ETN=" << myJunctionEntryTimeNeverYield
4591 << " CET=" << myJunctionConflictEntryTime
4592 << "\n";
4593 }
4594#endif
4595 if (hasArrivedInternal()) {
4596 break;
4597 }
4600 // abort lane change
4601 WRITE_WARNINGF("Vehicle '%' could not finish continuous lane change (turn lane) time=%.", getID(), time2string(SIMSTEP));
4603 }
4604 }
4605 if (approachedLane->getEdge().isVaporizing()) {
4607 break;
4608 }
4609 passedLanes.push_back(approachedLane);
4610 }
4611 }
4612 // NOTE: Passed drive items will be erased in the next simstep's planMove()
4613
4614#ifdef DEBUG_ACTIONSTEPS
4615 if (DEBUG_COND && myNextDriveItem != myLFLinkLanes.begin()) {
4616 std::cout << "Updated drive items:" << std::endl;
4617 for (DriveItemVector::iterator i = myLFLinkLanes.begin(); i != myLFLinkLanes.end(); ++i) {
4618 std::cout
4619 << " vPass=" << (*i).myVLinkPass
4620 << " vWait=" << (*i).myVLinkWait
4621 << " linkLane=" << ((*i).myLink == 0 ? "NULL" : (*i).myLink->getViaLaneOrLane()->getID())
4622 << " request=" << (*i).mySetRequest
4623 << "\n";
4624 }
4625 }
4626#endif
4627 } else if (!hasArrivedInternal() && myState.myPos < myLane->getLength() + NUMERICAL_EPS) {
4628 // avoid warning due to numerical instability when stopping at the end of the route
4630 }
4631
4632 }
4633}
4634
4635
4636
4637bool
4639#ifdef DEBUG_EXEC_MOVE
4640 if (DEBUG_COND) {
4641 std::cout << "\nEXECUTE_MOVE\n"
4642 << SIMTIME
4643 << " veh=" << getID()
4644 << " speed=" << getSpeed() // toString(getSpeed(), 24)
4645 << std::endl;
4646 }
4647#endif
4648
4649
4650 // Maximum safe velocity
4651 double vSafe = std::numeric_limits<double>::max();
4652 // Minimum safe velocity (lower bound).
4653 double vSafeMin = -std::numeric_limits<double>::max();
4654 // The distance to a link, which should either be crossed this step
4655 // or in front of which we need to stop.
4656 double vSafeMinDist = 0;
4657
4658 if (myActionStep) {
4659 // Actuate control (i.e. choose bounds for safe speed in current simstep (euler), resp. after current sim step (ballistic))
4660 processLinkApproaches(vSafe, vSafeMin, vSafeMinDist);
4661#ifdef DEBUG_ACTIONSTEPS
4662 if (DEBUG_COND) {
4663 std::cout << SIMTIME << " vehicle '" << getID() << "'\n"
4664 " vsafe from processLinkApproaches(): vsafe " << vSafe << std::endl;
4665 }
4666#endif
4667 } else {
4668 // Continue with current acceleration
4669 vSafe = getSpeed() + ACCEL2SPEED(myAcceleration);
4670#ifdef DEBUG_ACTIONSTEPS
4671 if (DEBUG_COND) {
4672 std::cout << SIMTIME << " vehicle '" << getID() << "' skips processLinkApproaches()\n"
4673 " continues with constant accel " << myAcceleration << "...\n"
4674 << "speed: " << getSpeed() << " -> " << vSafe << std::endl;
4675 }
4676#endif
4677 }
4678
4679
4680//#ifdef DEBUG_EXEC_MOVE
4681// if (DEBUG_COND) {
4682// std::cout << "vSafe = " << toString(vSafe,12) << "\n" << std::endl;
4683// }
4684//#endif
4685
4686 // Determine vNext = speed after current sim step (ballistic), resp. in current simstep (euler)
4687 // Call to finalizeSpeed applies speed reduction due to dawdling / lane changing but ensures minimum safe speed
4688 double vNext = vSafe;
4689 const MSCFModel& cfModel = getCarFollowModel();
4690 const double rawAccel = SPEED2ACCEL(MAX2(vNext, 0.) - myState.mySpeed);
4691 if (vNext <= SUMO_const_haltingSpeed * TS && myWaitingTime > MSGlobals::gStartupWaitThreshold && rawAccel <= accelThresholdForWaiting() && myActionStep) {
4693 } else if (isStopped()) {
4694 // do not apply startupDelay for waypoints
4695 if (cfModel.startupDelayStopped() && getNextStop().pars.speed <= 0) {
4697 } else {
4698 // do not apply startupDelay but signal that a stop has taken place
4700 }
4701 } else {
4702 // identify potential startup (before other effects reduce the speed again)
4704 }
4705 if (myActionStep) {
4706 vNext = cfModel.finalizeSpeed(this, vSafe);
4707 if (vNext > 0) {
4708 vNext = MAX2(vNext, vSafeMin);
4709 }
4710 }
4711 // (Leo) to avoid tiny oscillations (< 1e-10) of vNext in a standing vehicle column (observed for ballistic update), we cap off vNext
4712 // (We assure to do this only for vNext<<NUMERICAL_EPS since otherwise this would nullify the workaround for #2995
4713 // (Jakob) We also need to make sure to reach a stop at the start of the next edge
4714 if (fabs(vNext) < NUMERICAL_EPS_SPEED && (myStopDist > POSITION_EPS || (hasStops() && myCurrEdge == getNextStop().edge))) {
4715 vNext = 0.;
4716 }
4717#ifdef DEBUG_EXEC_MOVE
4718 if (DEBUG_COND) {
4719 std::cout << SIMTIME << " finalizeSpeed vSafe=" << vSafe << " vSafeMin=" << (vSafeMin == -std::numeric_limits<double>::max() ? "-Inf" : toString(vSafeMin))
4720 << " vNext=" << vNext << " (i.e. accel=" << SPEED2ACCEL(vNext - getSpeed()) << ")" << std::endl;
4721 }
4722#endif
4723
4724 // vNext may be higher than vSafe without implying a bug:
4725 // - when approaching a green light that suddenly switches to yellow
4726 // - when using unregulated junctions
4727 // - when using tau < step-size
4728 // - when using unsafe car following models
4729 // - when using TraCI and some speedMode / laneChangeMode settings
4730 //if (vNext > vSafe + NUMERICAL_EPS) {
4731 // WRITE_WARNING("vehicle '" + getID() + "' cannot brake hard enough to reach safe speed "
4732 // + toString(vSafe, 4) + ", moving at " + toString(vNext, 4) + " instead. time="
4733 // + time2string(MSNet::getInstance()->getCurrentTimeStep()) + ".");
4734 //}
4735
4737 vNext = MAX2(vNext, 0.);
4738 } else {
4739 // (Leo) Ballistic: negative vNext can be used to indicate a stop within next step.
4740 }
4741
4742 // Check for speed advices from the traci client
4743 vNext = processTraCISpeedControl(vSafe, vNext);
4744
4745 // the acceleration of a vehicle equipped with the elecHybrid device is restricted by the maximal power of the electric drive as well
4746 MSDevice_ElecHybrid* elecHybridOfVehicle = dynamic_cast<MSDevice_ElecHybrid*>(getDevice(typeid(MSDevice_ElecHybrid)));
4747 if (elecHybridOfVehicle != nullptr) {
4748 // this is the consumption given by the car following model-computed acceleration
4749 elecHybridOfVehicle->setConsum(elecHybridOfVehicle->consumption(*this, (vNext - this->getSpeed()) / TS, vNext));
4750 // but the maximum power of the electric motor may be lower
4751 // it needs to be converted from [W] to [Wh/s] (3600s / 1h) so that TS can be taken into account
4752 double maxPower = getEmissionParameters()->getDoubleOptional(SUMO_ATTR_MAXIMUMPOWER, 100000.) / 3600;
4753 if (elecHybridOfVehicle->getConsum() / TS > maxPower) {
4754 // no, we cannot accelerate that fast, recompute the maximum possible acceleration
4755 double accel = elecHybridOfVehicle->acceleration(*this, maxPower, this->getSpeed());
4756 // and update the speed of the vehicle
4757 vNext = MIN2(vNext, this->getSpeed() + accel * TS);
4758 vNext = MAX2(vNext, 0.);
4759 // and set the vehicle consumption to reflect this
4760 elecHybridOfVehicle->setConsum(elecHybridOfVehicle->consumption(*this, (vNext - this->getSpeed()) / TS, vNext));
4761 }
4762 }
4763
4764 setBrakingSignals(vNext);
4765
4766 // update position and speed
4767 int oldLaneOffset = myLane->getEdge().getNumLanes() - myLane->getIndex();
4768 const MSLane* oldLaneMaybeOpposite = myLane;
4770 // transform to the forward-direction lane, move and then transform back
4773 }
4774 updateState(vNext);
4775 updateWaitingTime(vNext);
4776
4777 // Lanes, which the vehicle touched at some moment of the executed simstep
4778 std::vector<MSLane*> passedLanes;
4779 // remember previous lane (myLane is updated in processLaneAdvances)
4780 const MSLane* oldLane = myLane;
4781 // Reason for a possible emergency stop
4782 std::string emergencyReason;
4783 processLaneAdvances(passedLanes, emergencyReason);
4784
4785 updateTimeLoss(vNext);
4787
4789 if (myState.myPos > myLane->getLength()) {
4790 if (emergencyReason == "") {
4791 emergencyReason = TL(" for unknown reasons");
4792 }
4793 WRITE_WARNINGF(TL("Vehicle '%' performs emergency stop at the end of lane '%'% (decel=%, offset=%), time=%."),
4794 getID(), myLane->getID(), emergencyReason, myAcceleration - myState.mySpeed,
4799 myState.mySpeed = 0;
4800 myAcceleration = 0;
4801 }
4802 const MSLane* oldBackLane = getBackLane();
4804 passedLanes.clear(); // ignore back occupation
4805 }
4806#ifdef DEBUG_ACTIONSTEPS
4807 if (DEBUG_COND) {
4808 std::cout << SIMTIME << " veh '" << getID() << "' updates further lanes." << std::endl;
4809 }
4810#endif
4812 if (passedLanes.size() > 1 && isRail()) {
4813 for (auto pi = passedLanes.rbegin(); pi != passedLanes.rend(); ++pi) {
4814 MSLane* pLane = *pi;
4815 if (pLane != myLane && std::find(myFurtherLanes.begin(), myFurtherLanes.end(), pLane) == myFurtherLanes.end()) {
4817 }
4818 }
4819 }
4820 // bestLanes need to be updated before lane changing starts. NOTE: This call is also a presumption for updateDriveItems()
4822 if (myLane != oldLane || oldBackLane != getBackLane()) {
4823 if (myLaneChangeModel->getShadowLane() != nullptr || getLateralOverlap() > POSITION_EPS) {
4824 // shadow lane must be updated if the front or back lane changed
4825 // either if we already have a shadowLane or if there is lateral overlap
4827 }
4829 // The vehicles target lane must be also be updated if the front or back lane changed
4831 }
4832 }
4833 setBlinkerInformation(); // needs updated bestLanes
4834 //change the blue light only for emergency vehicles SUMOVehicleClass
4836 setEmergencyBlueLight(MSNet::getInstance()->getCurrentTimeStep());
4837 }
4838 // must be done before angle computation
4839 // State needs to be reset for all vehicles before the next call to MSEdgeControl::changeLanes
4840 if (myActionStep) {
4841 // check (#2681): Can this be skipped?
4842 myLaneChangeModel->prepareStep(oldLaneMaybeOpposite->getRNG());
4843 } else {
4845#ifdef DEBUG_ACTIONSTEPS
4846 if (DEBUG_COND) {
4847 std::cout << SIMTIME << " veh '" << getID() << "' skips LCM->prepareStep()." << std::endl;
4848 }
4849#endif
4850 }
4853 }
4854
4855#ifdef DEBUG_EXEC_MOVE
4856 if (DEBUG_COND) {
4857 std::cout << SIMTIME << " executeMove finished veh=" << getID() << " lane=" << myLane->getID() << " myPos=" << getPositionOnLane() << " myPosLat=" << getLateralPositionOnLane() << "\n";
4858 gDebugFlag1 = false; // See MSLink_DEBUG_OPENED
4859 }
4860#endif
4862 // transform back to the opposite-direction lane
4863 MSLane* newOpposite = nullptr;
4864 const MSEdge* newOppositeEdge = myLane->getEdge().getOppositeEdge();
4865 if (newOppositeEdge != nullptr) {
4866 newOpposite = newOppositeEdge->getLanes()[newOppositeEdge->getNumLanes() - MAX2(1, oldLaneOffset)];
4867#ifdef DEBUG_EXEC_MOVE
4868 if (DEBUG_COND) {
4869 std::cout << SIMTIME << " newOppositeEdge=" << newOppositeEdge->getID() << " oldLaneOffset=" << oldLaneOffset << " leftMost=" << newOppositeEdge->getNumLanes() - 1 << " newOpposite=" << Named::getIDSecure(newOpposite) << "\n";
4870 }
4871#endif
4872 }
4873 if (newOpposite == nullptr) {
4875 // unusual overtaking at junctions is ok for emergency vehicles
4876 WRITE_WARNINGF(TL("Unexpected end of opposite lane for vehicle '%' at lane '%', time=%."),
4878 }
4880 if (myState.myPos < getLength()) {
4881 // further lanes is always cleared during opposite driving
4882 MSLane* oldOpposite = oldLane->getOpposite();
4883 if (oldOpposite != nullptr) {
4884 myFurtherLanes.push_back(oldOpposite);
4885 myFurtherLanesPosLat.push_back(0);
4886 // small value since the lane is going in the other direction
4889 } else {
4890 SOFT_ASSERT(false);
4891 }
4892 }
4893 } else {
4895 myLane = newOpposite;
4896 oldLane = oldLaneMaybeOpposite;
4897 //std::cout << SIMTIME << " updated myLane=" << Named::getIDSecure(myLane) << " oldLane=" << oldLane->getID() << "\n";
4900 }
4901 }
4902 // myAngle was already updated. Update lastAngle so moveRemindes have consisent angleDiff (after finalizeSpeed because it uses the old angles)
4904 // store angle before lane changing
4906
4908 // Return whether the vehicle did move to another lane
4909 return myLane != oldLane;
4910}
4911
4912void
4914 myState.myPos += dist;
4917
4918 const std::vector<const MSLane*> lanes = getUpcomingLanesUntil(dist);
4920 for (int i = 0; i < (int)lanes.size(); i++) {
4921 MSLink* link = nullptr;
4922 if (i + 1 < (int)lanes.size()) {
4923 const MSLane* const to = lanes[i + 1];
4924 const bool internal = to->isInternal();
4925 for (MSLink* const l : lanes[i]->getLinkCont()) {
4926 if ((internal && l->getViaLane() == to) || (!internal && l->getLane() == to)) {
4927 link = l;
4928 break;
4929 }
4930 }
4931 }
4932 myLFLinkLanes.emplace_back(link, getSpeed(), getSpeed(), true, t, getSpeed(), 0, 0, dist);
4933 }
4934 // minimum execute move:
4935 std::vector<MSLane*> passedLanes;
4936 // Reason for a possible emergency stop
4937 if (lanes.size() > 1) {
4939 }
4940 std::string emergencyReason;
4941 processLaneAdvances(passedLanes, emergencyReason);
4942#ifdef DEBUG_EXTRAPOLATE_DEPARTPOS
4943 if (DEBUG_COND) {
4944 std::cout << SIMTIME << " veh=" << getID() << " executeFractionalMove dist=" << dist
4945 << " passedLanes=" << toString(passedLanes) << " lanes=" << toString(lanes)
4946 << " finalPos=" << myState.myPos
4947 << " speed=" << getSpeed()
4948 << " myFurtherLanes=" << toString(myFurtherLanes)
4949 << "\n";
4950 }
4951#endif
4953 if (lanes.size() > 1) {
4954 for (std::vector<MSLane*>::iterator i = myFurtherLanes.begin(); i != myFurtherLanes.end(); ++i) {
4955#ifdef DEBUG_FURTHER
4956 if (DEBUG_COND) {
4957 std::cout << SIMTIME << " leaveLane \n";
4958 }
4959#endif
4960 (*i)->resetPartialOccupation(this);
4961 }
4962 myFurtherLanes.clear();
4963 myFurtherLanesPosLat.clear();
4965 }
4966}
4967
4968
4969void
4970MSVehicle::updateState(double vNext, bool parking) {
4971 // update position and speed
4972 double deltaPos; // positional change
4974 // euler
4975 deltaPos = SPEED2DIST(vNext);
4976 } else {
4977 // ballistic
4978 deltaPos = getDeltaPos(SPEED2ACCEL(vNext - myState.mySpeed));
4979 }
4980
4981 // the *mean* acceleration during the next step (probably most appropriate for emission calculation)
4982 // NOTE: for the ballistic update vNext may be negative, indicating a stop.
4984
4985#ifdef DEBUG_EXEC_MOVE
4986 if (DEBUG_COND) {
4987 std::cout << SIMTIME << " updateState() for veh '" << getID() << "': deltaPos=" << deltaPos
4988 << " pos=" << myState.myPos << " newPos=" << myState.myPos + deltaPos << std::endl;
4989 }
4990#endif
4991 double decelPlus = -myAcceleration - getCarFollowModel().getMaxDecel() - NUMERICAL_EPS;
4992 if (decelPlus > 0) {
4993 const double previousAcceleration = SPEED2ACCEL(myState.mySpeed - myState.myPreviousSpeed);
4994 if (myAcceleration + NUMERICAL_EPS < previousAcceleration) {
4995 // vehicle brakes beyond wished maximum deceleration (only warn at the start of the braking manoeuvre)
4996 decelPlus += 2 * NUMERICAL_EPS;
4997 const double emergencyFraction = decelPlus / MAX2(NUMERICAL_EPS, getCarFollowModel().getEmergencyDecel() - getCarFollowModel().getMaxDecel());
4998 if (emergencyFraction >= MSGlobals::gEmergencyDecelWarningThreshold) {
4999 WRITE_WARNINGF(TL("Vehicle '%' performs emergency braking on lane '%' with decel=%, wished=%, severity=%, time=%."),
5000 //+ " decelPlus=" + toString(decelPlus)
5001 //+ " prevAccel=" + toString(previousAcceleration)
5002 //+ " reserve=" + toString(MAX2(NUMERICAL_EPS, getCarFollowModel().getEmergencyDecel() - getCarFollowModel().getMaxDecel()))
5003 getID(), myLane->getID(), -myAcceleration, getCarFollowModel().getMaxDecel(), emergencyFraction, time2string(SIMSTEP));
5005 }
5006 }
5007 }
5008
5010 myState.mySpeed = MAX2(vNext, 0.);
5011
5012 if (isRemoteControlled()) {
5013 deltaPos = myInfluencer->implicitDeltaPosRemote(this);
5014 }
5015
5016 myState.myPos += deltaPos;
5017 myState.myLastCoveredDist = deltaPos;
5018 myNextTurn.first -= deltaPos;
5019
5020 if (!parking) {
5022 }
5023}
5024
5025void
5027 updateState(0, true);
5028 // deboard while parked
5029 if (myPersonDevice != nullptr) {
5031 }
5032 if (myContainerDevice != nullptr) {
5034 }
5035 for (MSVehicleDevice* const dev : myDevices) {
5036 dev->notifyParking();
5037 }
5038}
5039
5040
5041void
5047
5048
5049const MSLane*
5051 if (myFurtherLanes.size() > 0) {
5052 return myFurtherLanes.back();
5053 } else {
5054 return myLane;
5055 }
5056}
5057
5058
5059double
5060MSVehicle::updateFurtherLanes(std::vector<MSLane*>& furtherLanes, std::vector<double>& furtherLanesPosLat,
5061 const std::vector<MSLane*>& passedLanes) {
5062#ifdef DEBUG_SETFURTHER
5063 if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID()
5064 << " updateFurtherLanes oldFurther=" << toString(furtherLanes)
5065 << " oldFurtherPosLat=" << toString(furtherLanesPosLat)
5066 << " passed=" << toString(passedLanes)
5067 << "\n";
5068#endif
5069 for (MSLane* further : furtherLanes) {
5070 further->resetPartialOccupation(this);
5071 if (further->getBidiLane() != nullptr
5072 && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5073 further->getBidiLane()->resetPartialOccupation(this);
5074 }
5075 }
5076
5077 std::vector<MSLane*> newFurther;
5078 std::vector<double> newFurtherPosLat;
5079 double backPosOnPreviousLane = myState.myPos - getLength();
5080 bool widthShift = myFurtherLanesPosLat.size() > myFurtherLanes.size();
5081 if (passedLanes.size() > 1) {
5082 // There are candidates for further lanes. (passedLanes[-1] is the current lane, or current shadow lane in context of updateShadowLanes())
5083 std::vector<MSLane*>::const_iterator fi = furtherLanes.begin();
5084 std::vector<double>::const_iterator fpi = furtherLanesPosLat.begin();
5085 for (auto pi = passedLanes.rbegin() + 1; pi != passedLanes.rend() && backPosOnPreviousLane < 0; ++pi) {
5086 // As long as vehicle back reaches into passed lane, add it to the further lanes
5087 MSLane* further = *pi;
5088 newFurther.push_back(further);
5089 backPosOnPreviousLane += further->setPartialOccupation(this);
5090 if (further->getBidiLane() != nullptr
5091 && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5092 further->getBidiLane()->setPartialOccupation(this);
5093 }
5094 if (fi != furtherLanes.end() && further == *fi) {
5095 // Lateral position on this lane is already known. Assume constant and use old value.
5096 newFurtherPosLat.push_back(*fpi);
5097 ++fi;
5098 ++fpi;
5099 } else {
5100 // The lane *pi was not in furtherLanes before.
5101 // If it is downstream, we assume as lateral position the current position
5102 // If it is a new lane upstream (can appear as shadow further in case of LC-maneuvering, e.g.)
5103 // we assign the last known lateral position.
5104 if (newFurtherPosLat.size() == 0) {
5105 if (widthShift) {
5106 newFurtherPosLat.push_back(myFurtherLanesPosLat.back());
5107 } else {
5108 newFurtherPosLat.push_back(myState.myPosLat);
5109 }
5110 } else {
5111 newFurtherPosLat.push_back(newFurtherPosLat.back());
5112 }
5113 }
5114#ifdef DEBUG_SETFURTHER
5115 if (DEBUG_COND) {
5116 std::cout << SIMTIME << " updateFurtherLanes \n"
5117 << " further lane '" << further->getID() << "' backPosOnPreviousLane=" << backPosOnPreviousLane
5118 << std::endl;
5119 }
5120#endif
5121 }
5122 furtherLanes = newFurther;
5123 furtherLanesPosLat = newFurtherPosLat;
5124 } else {
5125 furtherLanes.clear();
5126 furtherLanesPosLat.clear();
5127 }
5128#ifdef DEBUG_SETFURTHER
5129 if (DEBUG_COND) std::cout
5130 << " newFurther=" << toString(furtherLanes)
5131 << " newFurtherPosLat=" << toString(furtherLanesPosLat)
5132 << " newBackPos=" << backPosOnPreviousLane
5133 << "\n";
5134#endif
5135 return backPosOnPreviousLane;
5136}
5137
5138
5139double
5140MSVehicle::getBackPositionOnLane(const MSLane* lane, bool calledByGetPosition) const {
5141#ifdef DEBUG_FURTHER
5142 if (DEBUG_COND) {
5143 std::cout << SIMTIME
5144 << " getBackPositionOnLane veh=" << getID()
5145 << " lane=" << Named::getIDSecure(lane)
5146 << " cbgP=" << calledByGetPosition
5147 << " pos=" << myState.myPos
5148 << " backPos=" << myState.myBackPos
5149 << " myLane=" << myLane->getID()
5150 << " myLaneBidi=" << Named::getIDSecure(myLane->getBidiLane())
5151 << " further=" << toString(myFurtherLanes)
5152 << " furtherPosLat=" << toString(myFurtherLanesPosLat)
5153 << "\n shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane())
5154 << " shadowFurther=" << toString(myLaneChangeModel->getShadowFurtherLanes())
5155 << " shadowFurtherPosLat=" << toString(myLaneChangeModel->getShadowFurtherLanesPosLat())
5156 << "\n targetLane=" << Named::getIDSecure(myLaneChangeModel->getTargetLane())
5157 << " furtherTargets=" << toString(myLaneChangeModel->getFurtherTargetLanes())
5158 << std::endl;
5159 }
5160#endif
5161 if (lane == myLane
5162 || lane == myLaneChangeModel->getShadowLane()
5163 || lane == myLaneChangeModel->getTargetLane()) {
5165 if (lane == myLaneChangeModel->getShadowLane()) {
5166 return lane->getLength() - myState.myPos - myType->getLength();
5167 } else {
5168 return myState.myPos + (calledByGetPosition ? -1 : 1) * myType->getLength();
5169 }
5170 } else if (&lane->getEdge() != &myLane->getEdge()) {
5171 return lane->getLength() - myState.myPos + (calledByGetPosition ? -1 : 1) * myType->getLength();
5172 } else {
5173 // account for parallel lanes of different lengths in the most conservative manner (i.e. while turning)
5174 return myState.myPos - myType->getLength() + MIN2(0.0, lane->getLength() - myLane->getLength());
5175 }
5176 } else if (lane == myLane->getBidiLane()) {
5177 return lane->getLength() - myState.myPos + myType->getLength() * (calledByGetPosition ? -1 : 1);
5178 } else if (myFurtherLanes.size() > 0 && lane == myFurtherLanes.back()) {
5179 return myState.myBackPos;
5180 } else if ((myLaneChangeModel->getShadowFurtherLanes().size() > 0 && lane == myLaneChangeModel->getShadowFurtherLanes().back())
5181 || (myLaneChangeModel->getFurtherTargetLanes().size() > 0 && lane == myLaneChangeModel->getFurtherTargetLanes().back())) {
5182 assert(myFurtherLanes.size() > 0);
5183 if (lane->getLength() == myFurtherLanes.back()->getLength()) {
5184 return myState.myBackPos;
5185 } else {
5186 // interpolate
5187 //if (DEBUG_COND) {
5188 //if (myFurtherLanes.back()->getLength() != lane->getLength()) {
5189 // std::cout << SIMTIME << " veh=" << getID() << " lane=" << lane->getID() << " further=" << myFurtherLanes.back()->getID()
5190 // << " len=" << lane->getLength() << " fLen=" << myFurtherLanes.back()->getLength()
5191 // << " backPos=" << myState.myBackPos << " result=" << myState.myBackPos / myFurtherLanes.back()->getLength() * lane->getLength() << "\n";
5192 //}
5193 return myState.myBackPos / myFurtherLanes.back()->getLength() * lane->getLength();
5194 }
5195 } else {
5196 //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myFurtherLanes=" << toString(myFurtherLanes) << "\n";
5197 double leftLength = myType->getLength() - myState.myPos;
5198
5199 std::vector<MSLane*>::const_iterator i = myFurtherLanes.begin();
5200 while (leftLength > 0 && i != myFurtherLanes.end()) {
5201 leftLength -= (*i)->getLength();
5202 //if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
5203 if (*i == lane) {
5204 return -leftLength;
5205 } else if (*i == lane->getBidiLane()) {
5206 return lane->getLength() + leftLength - (calledByGetPosition ? 2 * myType->getLength() : 0);
5207 }
5208 ++i;
5209 }
5210 //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myShadowFurtherLanes=" << toString(myLaneChangeModel->getShadowFurtherLanes()) << "\n";
5211 leftLength = myType->getLength() - myState.myPos;
5213 while (leftLength > 0 && i != myLaneChangeModel->getShadowFurtherLanes().end()) {
5214 leftLength -= (*i)->getLength();
5215 //if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
5216 if (*i == lane) {
5217 return -leftLength;
5218 } else if (*i == lane->getBidiLane()) {
5219 return lane->getLength() + leftLength - (calledByGetPosition ? 2 * myType->getLength() : 0);
5220 }
5221 ++i;
5222 }
5223 //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myFurtherTargetLanes=" << toString(myLaneChangeModel->getFurtherTargetLanes()) << "\n";
5224 leftLength = myType->getLength() - myState.myPos;
5225 i = getFurtherLanes().begin();
5226 const std::vector<MSLane*> furtherTargetLanes = myLaneChangeModel->getFurtherTargetLanes();
5227 auto j = furtherTargetLanes.begin();
5228 while (leftLength > 0 && j != furtherTargetLanes.end()) {
5229 leftLength -= (*i)->getLength();
5230 // if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
5231 if (*j == lane) {
5232 return -leftLength;
5233 } else if (*j == lane->getBidiLane()) {
5234 return lane->getLength() + leftLength - (calledByGetPosition ? 2 * myType->getLength() : 0);
5235 }
5236 ++i;
5237 ++j;
5238 }
5239 WRITE_WARNINGF("Request backPos of vehicle '%' for invalid lane '%' time=%.",
5241 SOFT_ASSERT(false);
5242 return myState.myBackPos;
5243 }
5244}
5245
5246
5247double
5249 return getBackPositionOnLane(lane, true) + myType->getLength();
5250}
5251
5252
5253bool
5255 return lane == myLane || lane == myLaneChangeModel->getShadowLane() || lane == myLane->getBidiLane();
5256}
5257
5258
5259void
5260MSVehicle::checkRewindLinkLanes(const double lengthsInFront, DriveItemVector& lfLinks) const {
5262 double seenSpace = -lengthsInFront;
5263#ifdef DEBUG_CHECKREWINDLINKLANES
5264 if (DEBUG_COND) {
5265 std::cout << "\nCHECK_REWIND_LINKLANES\n" << " veh=" << getID() << " lengthsInFront=" << lengthsInFront << "\n";
5266 };
5267#endif
5268 bool foundStopped = false;
5269 // compute available space until a stopped vehicle is found
5270 // this is the sum of non-interal lane length minus in-between vehicle lengths
5271 for (int i = 0; i < (int)lfLinks.size(); ++i) {
5272 // skip unset links
5273 DriveProcessItem& item = lfLinks[i];
5274#ifdef DEBUG_CHECKREWINDLINKLANES
5275 if (DEBUG_COND) std::cout << SIMTIME
5276 << " link=" << (item.myLink == 0 ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
5277 << " foundStopped=" << foundStopped;
5278#endif
5279 if (item.myLink == nullptr || foundStopped) {
5280 if (!foundStopped) {
5281 item.availableSpace += seenSpace;
5282 } else {
5283 item.availableSpace = seenSpace;
5284 }
5285#ifdef DEBUG_CHECKREWINDLINKLANES
5286 if (DEBUG_COND) {
5287 std::cout << " avail=" << item.availableSpace << "\n";
5288 }
5289#endif
5290 continue;
5291 }
5292 // get the next lane, determine whether it is an internal lane
5293 const MSLane* approachedLane = item.myLink->getViaLane();
5294 if (approachedLane != nullptr) {
5295 if (keepClear(item.myLink)) {
5296 seenSpace = seenSpace - approachedLane->getBruttoVehLenSum();
5297 if (approachedLane == myLane) {
5298 seenSpace += getVehicleType().getLengthWithGap();
5299 }
5300 } else {
5301 seenSpace = seenSpace + approachedLane->getSpaceTillLastStanding(this, foundStopped);// - approachedLane->getBruttoVehLenSum() + approachedLane->getLength();
5302 }
5303 item.availableSpace = seenSpace;
5304#ifdef DEBUG_CHECKREWINDLINKLANES
5305 if (DEBUG_COND) std::cout
5306 << " approached=" << approachedLane->getID()
5307 << " approachedBrutto=" << approachedLane->getBruttoVehLenSum()
5308 << " avail=" << item.availableSpace
5309 << " seenSpace=" << seenSpace
5310 << " hadStoppedVehicle=" << item.hadStoppedVehicle
5311 << " lengthsInFront=" << lengthsInFront
5312 << "\n";
5313#endif
5314 continue;
5315 }
5316 approachedLane = item.myLink->getLane();
5317 const MSVehicle* last = approachedLane->getLastAnyVehicle();
5318 if (last == nullptr || last == this) {
5319 if (approachedLane->getLength() > getVehicleType().getLength()
5320 || keepClear(item.myLink)) {
5321 seenSpace += approachedLane->getLength();
5322 }
5323 item.availableSpace = seenSpace;
5324#ifdef DEBUG_CHECKREWINDLINKLANES
5325 if (DEBUG_COND) {
5326 std::cout << " last=" << Named::getIDSecure(last) << " laneLength=" << approachedLane->getLength() << " avail=" << item.availableSpace << "\n";
5327 }
5328#endif
5329 } else {
5330 bool foundStopped2 = false;
5331 double spaceTillLastStanding = approachedLane->getSpaceTillLastStanding(this, foundStopped2);
5332 if (approachedLane->getBidiLane() != nullptr) {
5333 const MSVehicle* oncomingVeh = approachedLane->getBidiLane()->getFirstFullVehicle();
5334 if (oncomingVeh) {
5335 const double oncomingGap = approachedLane->getLength() - oncomingVeh->getPositionOnLane();
5336 const double oncomingBGap = oncomingVeh->getBrakeGap(true);
5337 // oncoming movement until ego enters the junction
5338 const double oncomingMove = STEPS2TIME(item.myArrivalTime - SIMSTEP) * oncomingVeh->getSpeed();
5339 const double spaceTillOncoming = oncomingGap - oncomingBGap - oncomingMove;
5340 spaceTillLastStanding = MIN2(spaceTillLastStanding, spaceTillOncoming);
5341 if (spaceTillOncoming <= getVehicleType().getLengthWithGap()) {
5342 foundStopped = true;
5343 }
5344#ifdef DEBUG_CHECKREWINDLINKLANES
5345 if (DEBUG_COND) {
5346 std::cout << " oVeh=" << oncomingVeh->getID()
5347 << " oGap=" << oncomingGap
5348 << " bGap=" << oncomingBGap
5349 << " mGap=" << oncomingMove
5350 << " sto=" << spaceTillOncoming;
5351 }
5352#endif
5353 }
5354 }
5355 seenSpace += spaceTillLastStanding;
5356 if (foundStopped2) {
5357 foundStopped = true;
5358 item.hadStoppedVehicle = true;
5359 }
5360 item.availableSpace = seenSpace;
5361 if (last->myHaveToWaitOnNextLink || last->isStopped()) {
5362 foundStopped = true;
5363 item.hadStoppedVehicle = true;
5364 }
5365#ifdef DEBUG_CHECKREWINDLINKLANES
5366 if (DEBUG_COND) std::cout
5367 << " approached=" << approachedLane->getID()
5368 << " last=" << last->getID()
5369 << " lastHasToWait=" << last->myHaveToWaitOnNextLink
5370 << " lastBrakeLight=" << last->signalSet(VEH_SIGNAL_BRAKELIGHT)
5371 << " lastBrakeGap=" << last->getCarFollowModel().brakeGap(last->getSpeed())
5372 << " lastGap=" << (last->getBackPositionOnLane(approachedLane) + last->getCarFollowModel().brakeGap(last->getSpeed()) - last->getSpeed() * last->getCarFollowModel().getHeadwayTime()
5373 // gap of last up to the next intersection
5374 - last->getVehicleType().getMinGap())
5375 << " stls=" << spaceTillLastStanding
5376 << " avail=" << item.availableSpace
5377 << " seenSpace=" << seenSpace
5378 << " foundStopped=" << foundStopped
5379 << " foundStopped2=" << foundStopped2
5380 << "\n";
5381#endif
5382 }
5383 }
5384
5385 // check which links allow continuation and add pass available to the previous item
5386 for (int i = ((int)lfLinks.size() - 1); i > 0; --i) {
5387 DriveProcessItem& item = lfLinks[i - 1];
5388 DriveProcessItem& nextItem = lfLinks[i];
5389 const bool canLeaveJunction = item.myLink->getViaLane() == nullptr || nextItem.myLink == nullptr || nextItem.mySetRequest;
5390 const bool opened = (item.myLink != nullptr
5391 && (canLeaveJunction || (
5392 // indirect bicycle turn
5393 nextItem.myLink != nullptr && nextItem.myLink->isInternalJunctionLink() && nextItem.myLink->haveRed()))
5394 && (
5395 item.myLink->havePriority()
5396 || i == 1 // the upcoming link (item 0) is checked in executeMove anyway. No need to use outdata approachData here
5398 || item.myLink->opened(item.myArrivalTime, item.myArrivalSpeed,
5401 bool allowsContinuation = (item.myLink == nullptr || item.myLink->isCont() || opened) && !item.hadStoppedVehicle;
5402#ifdef DEBUG_CHECKREWINDLINKLANES
5403 if (DEBUG_COND) std::cout
5404 << " link=" << (item.myLink == 0 ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
5405 << " canLeave=" << canLeaveJunction
5406 << " opened=" << opened
5407 << " allowsContinuation=" << allowsContinuation
5408 << " foundStopped=" << foundStopped
5409 << "\n";
5410#endif
5411 if (!opened && item.myLink != nullptr) {
5412 foundStopped = true;
5413 if (i > 1) {
5414 DriveProcessItem& item2 = lfLinks[i - 2];
5415 if (item2.myLink != nullptr && item2.myLink->isCont()) {
5416 allowsContinuation = true;
5417 }
5418 }
5419 }
5420 if (allowsContinuation) {
5421 item.availableSpace = nextItem.availableSpace;
5422#ifdef DEBUG_CHECKREWINDLINKLANES
5423 if (DEBUG_COND) std::cout
5424 << " link=" << (item.myLink == nullptr ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
5425 << " copy nextAvail=" << nextItem.availableSpace
5426 << "\n";
5427#endif
5428 }
5429 }
5430
5431 // find removalBegin
5432 int removalBegin = -1;
5433 for (int i = 0; foundStopped && i < (int)lfLinks.size() && removalBegin < 0; ++i) {
5434 // skip unset links
5435 const DriveProcessItem& item = lfLinks[i];
5436 if (item.myLink == nullptr) {
5437 continue;
5438 }
5439 /*
5440 double impatienceCorrection = MAX2(0., double(double(myWaitingTime)));
5441 if (seenSpace<getVehicleType().getLengthWithGap()-impatienceCorrection/10.&&nextSeenNonInternal!=0) {
5442 removalBegin = lastLinkToInternal;
5443 }
5444 */
5445
5446 const double leftSpace = item.availableSpace - getVehicleType().getLengthWithGap();
5447#ifdef DEBUG_CHECKREWINDLINKLANES
5448 if (DEBUG_COND) std::cout
5449 << SIMTIME
5450 << " veh=" << getID()
5451 << " link=" << (item.myLink == 0 ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
5452 << " avail=" << item.availableSpace
5453 << " leftSpace=" << leftSpace
5454 << "\n";
5455#endif
5456 if (leftSpace < 0/* && item.myLink->willHaveBlockedFoe()*/) {
5457 double impatienceCorrection = 0;
5458 /*
5459 if(item.myLink->getState()==LINKSTATE_MINOR) {
5460 impatienceCorrection = MAX2(0., STEPS2TIME(myWaitingTime));
5461 }
5462 */
5463 // may ignore keepClear rules
5464 if (leftSpace < -impatienceCorrection / 10. && keepClear(item.myLink)) {
5465 removalBegin = i;
5466 }
5467 //removalBegin = i;
5468 }
5469 }
5470 // abort requests
5471 if (removalBegin != -1 && !(removalBegin == 0 && myLane->getEdge().isInternal())) {
5472 const double brakeGap = getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0.);
5473 while (removalBegin < (int)(lfLinks.size())) {
5474 DriveProcessItem& dpi = lfLinks[removalBegin];
5475 if (dpi.myLink == nullptr) {
5476 break;
5477 }
5478 dpi.myVLinkPass = dpi.myVLinkWait;
5479#ifdef DEBUG_CHECKREWINDLINKLANES
5480 if (DEBUG_COND) {
5481 std::cout << " removalBegin=" << removalBegin << " brakeGap=" << brakeGap << " dist=" << dpi.myDistance << " speed=" << myState.mySpeed << " a2s=" << ACCEL2SPEED(getCarFollowModel().getMaxDecel()) << "\n";
5482 }
5483#endif
5484 if (dpi.myDistance >= brakeGap + POSITION_EPS) {
5485 // always leave junctions after requesting to enter
5486 if (!dpi.myLink->isExitLink() || !lfLinks[removalBegin - 1].mySetRequest) {
5487 dpi.mySetRequest = false;
5488 }
5489 }
5490 ++removalBegin;
5491 }
5492 }
5493 }
5494}
5495
5496
5497void
5499 if (!myActionStep) {
5500 return;
5501 }
5502 // links approached in both steps are updated in place, the others are removed
5503 auto approaches = [](const DriveItemVector & items, DriveItemVector::const_iterator end, const MSLink * link) {
5504 for (DriveItemVector::const_iterator it = items.begin(); it != end; ++it) {
5505 if (it->myLink == link) {
5506 return true;
5507 }
5508 }
5509 return false;
5510 };
5511 for (const DriveProcessItem& dpi : myLFLinkLanesPrev) {
5512 if (dpi.myLink != nullptr && !approaches(myLFLinkLanes, myLFLinkLanes.end(), dpi.myLink)) {
5513 dpi.myLink->removeApproaching(this);
5514 }
5515 }
5517 for (DriveItemVector::iterator it = myLFLinkLanes.begin(); it != myLFLinkLanes.end(); ++it) {
5518 DriveProcessItem& dpi = *it;
5519 if (dpi.myLink != nullptr) {
5520 if (dpi.myLink->getState() == LINKSTATE_ALLWAY_STOP) {
5521 dpi.myArrivalTime += (SUMOTime)RandHelper::rand((int)2, getRNG()); // tie braker
5522 }
5523 // only the first registration counts on looped routes (emplace keeps it)
5524 if (approaches(myLFLinkLanesPrev, myLFLinkLanesPrev.end(), dpi.myLink) && !approaches(myLFLinkLanes, it, dpi.myLink)) {
5527 } else {
5530 }
5531 }
5532 }
5533 if (isRail()) {
5534 for (DriveProcessItem& dpi : myLFLinkLanes) {
5535 if (dpi.myLink != nullptr && dpi.myLink->getTLLogic() != nullptr && dpi.myLink->getTLLogic()->getLogicType() == TrafficLightType::RAIL_SIGNAL) {
5537 }
5538 }
5539 }
5540 if (myLaneChangeModel->getShadowLane() != nullptr) {
5541 // register on all shadow links
5542 for (const DriveProcessItem& dpi : myLFLinkLanes) {
5543 if (dpi.myLink != nullptr) {
5544 MSLink* parallelLink = dpi.myLink->getParallelLink(myLaneChangeModel->getShadowDirection());
5545 if (parallelLink == nullptr && getLaneChangeModel().isOpposite() && dpi.myLink->isEntryLink()) {
5546 // register on opposite direction entry link to warn foes at minor side road
5547 parallelLink = dpi.myLink->getOppositeDirectionLink();
5548 }
5549 if (parallelLink != nullptr) {
5550 const double latOffset = getLane()->getRightSideOnEdge() - myLaneChangeModel->getShadowLane()->getRightSideOnEdge();
5551 parallelLink->setApproaching(this, dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
5552 dpi.mySetRequest, dpi.myArrivalSpeedBraking, getWaitingTimeFor(dpi.myLink), dpi.myDistance,
5553 latOffset);
5555 }
5556 }
5557 }
5558 }
5559#ifdef DEBUG_PLAN_MOVE
5560 if (DEBUG_COND) {
5561 std::cout << SIMTIME
5562 << " veh=" << getID()
5563 << " after checkRewindLinkLanes\n";
5564 for (DriveProcessItem& dpi : myLFLinkLanes) {
5565 std::cout
5566 << " vPass=" << dpi.myVLinkPass
5567 << " vWait=" << dpi.myVLinkWait
5568 << " linkLane=" << (dpi.myLink == 0 ? "NULL" : dpi.myLink->getViaLaneOrLane()->getID())
5569 << " request=" << dpi.mySetRequest
5570 << " atime=" << dpi.myArrivalTime
5571 << "\n";
5572 }
5573 }
5574#endif
5575}
5576
5577
5578void
5580 DriveProcessItem dpi(0, dist);
5581 dpi.myLink = link;
5582 const double arrivalSpeedBraking = getCarFollowModel().getMinimalArrivalSpeedEuler(dist, getSpeed());
5583 link->setApproaching(this, SUMOTime_MAX, 0, 0, false, arrivalSpeedBraking, 0, dpi.myDistance, 0);
5584 // ensure cleanup in the next step
5585 myLFLinkLanes.push_back(dpi);
5587}
5588
5589
5590void
5591MSVehicle::enterLaneAtMove(MSLane* enteredLane, bool onTeleporting) {
5592 myAmOnNet = !onTeleporting;
5593 // vaporizing edge?
5594 /*
5595 if (enteredLane->getEdge().isVaporizing()) {
5596 // yep, let's do the vaporization...
5597 myLane = enteredLane;
5598 return true;
5599 }
5600 */
5601 // Adjust MoveReminder offset to the next lane
5602 adaptLaneEntering2MoveReminder(*enteredLane);
5603 // set the entered lane as the current lane
5604 MSLane* oldLane = myLane;
5605 myLane = enteredLane;
5606 myLastBestLanesEdge = nullptr;
5607
5608 // internal edges are not a part of the route...
5609 if (!enteredLane->getEdge().isInternal()) {
5610 ++myCurrEdge;
5612 }
5613 if (myInfluencer != nullptr) {
5615 }
5616 if (!onTeleporting) {
5620 // transform lateral position when the lane width changes
5621 assert(oldLane != nullptr);
5622 const MSLink* const link = oldLane->getLinkTo(myLane);
5623 if (link != nullptr) {
5624 myState.myPosLat += link->getLateralShift();
5625 } else {
5627 }
5628 } else if (fabs(myState.myPosLat) > NUMERICAL_EPS) {
5629 const double overlap = MAX2(0.0, getLateralOverlap(myState.myPosLat, oldLane));
5630 const double range = (oldLane->getWidth() - getVehicleType().getWidth()) * 0.5 + overlap;
5631 const double range2 = (myLane->getWidth() - getVehicleType().getWidth()) * 0.5 + overlap;
5632 myState.myPosLat *= range2 / range;
5633 }
5634 if (myLane->getBidiLane() != nullptr && (!isRailway(getVClass()) || (myLane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5635 // railways don't need to "see" each other when moving in opposite directions on the same track (efficiency)
5636 // (unless the lane is shared with cars)
5638 }
5639 } else {
5640 // normal move() isn't called so reset position here. must be done
5641 // before calling reminders
5642 myState.myPos = 0;
5645 }
5646 // update via
5647 if (myParameter->via.size() > 0 && myLane->getEdge().getID() == myParameter->via.front()) {
5648 myParameter->via.erase(myParameter->via.begin());
5649 }
5650}
5651
5652
5653void
5655 myAmOnNet = true;
5656 myLane = enteredLane;
5658 // need to update myCurrentLaneInBestLanes
5660 // switch to and activate the new lane's reminders
5661 // keep OldLaneReminders
5662 for (std::vector< MSMoveReminder* >::const_iterator rem = enteredLane->getMoveReminders().begin(); rem != enteredLane->getMoveReminders().end(); ++rem) {
5663 addReminder(*rem);
5664 }
5666 MSLane* lane = myLane;
5667 double leftLength = getVehicleType().getLength() - myState.myPos;
5668 int deleteFurther = 0;
5669#ifdef DEBUG_SETFURTHER
5670 if (DEBUG_COND) {
5671 std::cout << SIMTIME << " enterLaneAtLaneChange entered=" << Named::getIDSecure(enteredLane) << " oldFurther=" << toString(myFurtherLanes) << "\n";
5672 }
5673#endif
5674 if (myLane->getBidiLane() != nullptr && (!isRailway(getVClass()) || (myLane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5675 // railways don't need to "see" each other when moving in opposite directions on the same track (efficiency)
5676 // (unless the lane is shared with cars)
5678 }
5679 for (int i = 0; i < (int)myFurtherLanes.size(); i++) {
5680 if (lane != nullptr) {
5682 }
5683#ifdef DEBUG_SETFURTHER
5684 if (DEBUG_COND) {
5685 std::cout << " enterLaneAtLaneChange i=" << i << " lane=" << Named::getIDSecure(lane) << " leftLength=" << leftLength << "\n";
5686 }
5687#endif
5688 if (leftLength > 0) {
5689 if (lane != nullptr) {
5691 if (myFurtherLanes[i]->getBidiLane() != nullptr
5692 && (!isRailway(getVClass()) || (myFurtherLanes[i]->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5693 myFurtherLanes[i]->getBidiLane()->resetPartialOccupation(this);
5694 }
5695 // lane changing onto longer lanes may reduce the number of
5696 // remaining further lanes
5697 myFurtherLanes[i] = lane;
5699 leftLength -= lane->setPartialOccupation(this);
5700 if (lane->getBidiLane() != nullptr
5701 && (!isRailway(getVClass()) || (lane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5702 lane->getBidiLane()->setPartialOccupation(this);
5703 }
5704 myState.myBackPos = -leftLength;
5705#ifdef DEBUG_SETFURTHER
5706 if (DEBUG_COND) {
5707 std::cout << SIMTIME << " newBackPos=" << myState.myBackPos << "\n";
5708 }
5709#endif
5710 } else {
5711 // keep the old values, but ensure there is no shadow
5714 }
5715 if (myState.myBackPos < 0) {
5716 myState.myBackPos += myFurtherLanes[i]->getLength();
5717 }
5718#ifdef DEBUG_SETFURTHER
5719 if (DEBUG_COND) {
5720 std::cout << SIMTIME << " i=" << i << " further=" << myFurtherLanes[i]->getID() << " newBackPos=" << myState.myBackPos << "\n";
5721 }
5722#endif
5723 }
5724 } else {
5725 myFurtherLanes[i]->resetPartialOccupation(this);
5726 if (myFurtherLanes[i]->getBidiLane() != nullptr
5727 && (!isRailway(getVClass()) || (myFurtherLanes[i]->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5728 myFurtherLanes[i]->getBidiLane()->resetPartialOccupation(this);
5729 }
5730 deleteFurther++;
5731 }
5732 }
5733 if (deleteFurther > 0) {
5734#ifdef DEBUG_SETFURTHER
5735 if (DEBUG_COND) {
5736 std::cout << SIMTIME << " veh=" << getID() << " shortening myFurtherLanes by " << deleteFurther << "\n";
5737 }
5738#endif
5739 myFurtherLanes.erase(myFurtherLanes.end() - deleteFurther, myFurtherLanes.end());
5740 myFurtherLanesPosLat.erase(myFurtherLanesPosLat.end() - deleteFurther, myFurtherLanesPosLat.end());
5741 }
5742#ifdef DEBUG_SETFURTHER
5743 if (DEBUG_COND) {
5744 std::cout << SIMTIME << " enterLaneAtLaneChange new furtherLanes=" << toString(myFurtherLanes)
5745 << " furterLanesPosLat=" << toString(myFurtherLanesPosLat) << "\n";
5746 }
5747#endif
5749}
5750
5751
5752void
5753MSVehicle::computeFurtherLanes(MSLane* enteredLane, double pos, bool collision) {
5754 // build the list of lanes the vehicle is lapping into
5755 if (!myLaneChangeModel->isOpposite()) {
5756 double leftLength = myType->getLength() - pos;
5757 MSLane* clane = enteredLane;
5758 int routeIndex = getRoutePosition();
5759 while (leftLength > 0) {
5760 bool guessed = false;
5761 if (routeIndex > 0 && clane->getEdge().isNormal()) {
5762 // get predecessor lane that corresponds to prior route
5763 routeIndex--;
5764 const MSEdge* fromRouteEdge = myRoute->getEdges()[routeIndex];
5765 MSLane* target = clane;
5766 clane = nullptr;
5767 for (auto ili : target->getIncomingLanes()) {
5768 if (ili.lane->getEdge().getNormalBefore() == fromRouteEdge) {
5769 clane = ili.lane;
5770 break;
5771 }
5772 }
5773 } else {
5774 // only the predecessor of a normal lane is a guess
5775 guessed = clane->getEdge().isNormal();
5776 clane = clane->getLogicalPredecessorLane();
5777 }
5778 if (clane == nullptr || clane == myLane || clane == myLane->getBidiLane()
5779 || (guessed && clane->isInternal() && (
5780 clane->getLinkCont()[0]->getDirection() == LinkDirection::TURN
5781 || clane->getLinkCont()[0]->getDirection() == LinkDirection::TURN_LEFTHAND))) {
5782 break;
5783 }
5784 if (!collision || std::find(myFurtherLanes.begin(), myFurtherLanes.end(), clane) == myFurtherLanes.end()) {
5785 myFurtherLanes.push_back(clane);
5787 clane->setPartialOccupation(this);
5788 if (clane->getBidiLane() != nullptr
5789 && (!isRailway(getVClass()) || (clane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5790 clane->getBidiLane()->setPartialOccupation(this);
5791 }
5792 }
5793 leftLength -= clane->getLength();
5794 }
5795 myState.myBackPos = -leftLength;
5796#ifdef DEBUG_SETFURTHER
5797 if (DEBUG_COND) {
5798 std::cout << SIMTIME << " computeFurtherLanes veh=" << getID() << " pos=" << pos << " myFurtherLanes=" << toString(myFurtherLanes) << " backPos=" << myState.myBackPos << "\n";
5799 }
5800#endif
5801 } else {
5802 // clear partial occupation
5803 for (MSLane* further : myFurtherLanes) {
5804#ifdef DEBUG_SETFURTHER
5805 if (DEBUG_COND) {
5806 std::cout << SIMTIME << " opposite: resetPartialOccupation " << further->getID() << " \n";
5807 }
5808#endif
5809 further->resetPartialOccupation(this);
5810 if (further->getBidiLane() != nullptr
5811 && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5812 further->getBidiLane()->resetPartialOccupation(this);
5813 }
5814 }
5815 myFurtherLanes.clear();
5816 myFurtherLanesPosLat.clear();
5817 }
5818}
5819
5820
5821void
5822MSVehicle::enterLaneAtInsertion(MSLane* enteredLane, double pos, double speed, double posLat, MSMoveReminder::Notification notification) {
5823 myState = State(pos, speed, posLat, pos - getVehicleType().getLength(), hasDeparted() ? myState.myPreviousSpeed : speed);
5825 onDepart();
5826 }
5827 if (enteredLane->isInternal() && myJunctionEntryTime == SUMOTime_MAX) {
5830 assert(enteredLane->getIncomingLanes().size() == 1);
5831 if (enteredLane->getIncomingLanes().front().viaLink->isConflictEntryLink()) {
5833 }
5834 }
5836 assert(myState.myPos >= 0);
5837 assert(myState.mySpeed >= 0);
5838 myLane = enteredLane;
5839 myAmOnNet = true;
5840 // schedule action for the next timestep
5842 if (notification != MSMoveReminder::NOTIFICATION_TELEPORT) {
5843 if (notification == MSMoveReminder::NOTIFICATION_PARKING && myInfluencer != nullptr) {
5844 drawOutsideNetwork(false);
5845 }
5846 // set and activate the new lane's reminders, teleports already did that at enterLaneAtMove
5847 for (std::vector< MSMoveReminder* >::const_iterator rem = enteredLane->getMoveReminders().begin(); rem != enteredLane->getMoveReminders().end(); ++rem) {
5848 addReminder(*rem);
5849 }
5850 activateReminders(notification, enteredLane);
5851 } else {
5852 myLastBestLanesEdge = nullptr;
5855 while (!myStops.empty() && myStops.front().edge == myCurrEdge && &myStops.front().lane->getEdge() == &myLane->getEdge()
5856 && myStops.front().pars.endPos < pos) {
5857 WRITE_WARNINGF(TL("Vehicle '%' skips stop on lane '%' time=%."), getID(), myStops.front().lane->getID(),
5858 time2string(MSNet::getInstance()->getCurrentTimeStep()));
5860 myStops.pop_front();
5861 }
5862 // avoid startup-effects after teleport
5864 myStopSpeed = std::numeric_limits<double>::max();
5865 }
5866 computeFurtherLanes(enteredLane, pos);
5870 } else if (MSGlobals::gLaneChangeDuration > 0) {
5872 }
5873 if (notification != MSMoveReminder::NOTIFICATION_LOAD_STATE) {
5877 myAngle += M_PI;
5878 }
5879 }
5880 if (MSNet::getInstance()->hasPersons()) {
5881 for (MSLane* further : myFurtherLanes) {
5882 if (further->mustCheckJunctionCollisions()) {
5884 }
5885 }
5886 }
5887}
5888
5889
5890void
5891MSVehicle::leaveLane(const MSMoveReminder::Notification reason, const MSLane* approachedLane) {
5892 for (MoveReminderCont::iterator rem = myMoveReminders.begin(); rem != myMoveReminders.end();) {
5893 if (rem->first->notifyLeave(*this, myState.myPos + rem->second, reason, approachedLane)) {
5894#ifdef _DEBUG
5895 if (myTraceMoveReminders) {
5896 traceMoveReminder("notifyLeave", rem->first, rem->second, true);
5897 }
5898#endif
5899 ++rem;
5900 } else {
5901#ifdef _DEBUG
5902 if (myTraceMoveReminders) {
5903 traceMoveReminder("notifyLeave", rem->first, rem->second, false);
5904 }
5905#endif
5906 rem = myMoveReminders.erase(rem);
5907 }
5908 }
5912 && myLane != nullptr) {
5914 }
5915 if (myLane != nullptr && myLane->getBidiLane() != nullptr && myAmOnNet
5916 && (!isRailway(getVClass()) || (myLane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5918 }
5920 // @note. In case of lane change, myFurtherLanes and partial occupation
5921 // are handled in enterLaneAtLaneChange()
5922 for (MSLane* further : myFurtherLanes) {
5923#ifdef DEBUG_FURTHER
5924 if (DEBUG_COND) {
5925 std::cout << SIMTIME << " leaveLane \n";
5926 }
5927#endif
5928 further->resetPartialOccupation(this);
5929 if (further->getBidiLane() != nullptr
5930 && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5931 further->getBidiLane()->resetPartialOccupation(this);
5932 }
5933 }
5934 myFurtherLanes.clear();
5935 myFurtherLanesPosLat.clear();
5936 }
5938 myAmOnNet = false;
5939 myWaitingTime = 0;
5940 }
5942 myStopDist = std::numeric_limits<double>::max();
5943 if (myPastStops.back().speed <= 0) {
5944 WRITE_WARNINGF(TL("Vehicle '%' aborts stop."), getID());
5945 }
5946 }
5948 while (!myStops.empty() && myStops.front().edge == myCurrEdge && &myStops.front().lane->getEdge() == &myLane->getEdge()) {
5949 if (myStops.front().getSpeed() <= 0) {
5950 WRITE_WARNINGF(TL("Vehicle '%' skips stop on lane '%' time=%."), getID(), myStops.front().lane->getID(),
5951 time2string(MSNet::getInstance()->getCurrentTimeStep()));
5953 if (MSStopOut::active()) {
5954 // clean up if stopBlocked was called
5956 }
5957 myStops.pop_front();
5958 } else {
5959 MSStop& stop = myStops.front();
5960 // passed waypoint at the end of the lane
5961 if (!stop.reached) {
5962 if (MSStopOut::active()) {
5964 }
5965 stop.reached = true;
5966 // enter stopping place so leaveFrom works as expected
5967 if (stop.busstop != nullptr) {
5968 // let the bus stop know the vehicle
5969 stop.busstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
5970 }
5971 if (stop.containerstop != nullptr) {
5972 // let the container stop know the vehicle
5974 }
5975 // do not enter parkingarea!
5976 if (stop.chargingStation != nullptr) {
5977 // let the container stop know the vehicle
5979 }
5980 }
5982 }
5983 myStopDist = std::numeric_limits<double>::max();
5984 }
5985 }
5986}
5987
5988
5989void
5991 for (MoveReminderCont::iterator rem = myMoveReminders.begin(); rem != myMoveReminders.end();) {
5992 if (rem->first->notifyLeaveBack(*this, reason, leftLane)) {
5993#ifdef _DEBUG
5994 if (myTraceMoveReminders) {
5995 traceMoveReminder("notifyLeaveBack", rem->first, rem->second, true);
5996 }
5997#endif
5998 ++rem;
5999 } else {
6000#ifdef _DEBUG
6001 if (myTraceMoveReminders) {
6002 traceMoveReminder("notifyLeaveBack", rem->first, rem->second, false);
6003 }
6004#endif
6005 rem = myMoveReminders.erase(rem);
6006 }
6007 }
6008#ifdef DEBUG_MOVEREMINDERS
6009 if (DEBUG_COND) {
6010 std::cout << SIMTIME << " veh=" << getID() << " myReminders:";
6011 for (auto rem : myMoveReminders) {
6012 std::cout << rem.first->getDescription() << " ";
6013 }
6014 std::cout << "\n";
6015 }
6016#endif
6017}
6018
6019
6024
6025
6030
6031bool
6033 return (lane->isInternal()
6034 ? & (lane->getLinkCont()[0]->getLane()->getEdge()) != *(myCurrEdge + 1)
6035 : &lane->getEdge() != *myCurrEdge);
6036}
6037
6038const std::vector<MSVehicle::LaneQ>&
6040 return *myBestLanes.begin();
6041}
6042
6043
6044void
6045MSVehicle::updateBestLanes(bool forceRebuild, const MSLane* startLane) {
6046#ifdef DEBUG_BESTLANES
6047 if (DEBUG_COND) {
6048 std::cout << SIMTIME << " updateBestLanes veh=" << getID() << " force=" << forceRebuild << " startLane1=" << Named::getIDSecure(startLane) << " myLane=" << Named::getIDSecure(myLane) << "\n";
6049 }
6050#endif
6051 if (startLane == nullptr) {
6052 startLane = myLane;
6053 }
6054 assert(startLane != 0);
6056 // depending on the calling context, startLane might be the forward lane
6057 // or the reverse-direction lane. In the latter case we need to
6058 // transform it to the forward lane.
6059 if (isOppositeLane(startLane)) {
6060 // use leftmost lane of forward edge
6061 startLane = startLane->getEdge().getOppositeEdge()->getLanes().back();
6062 assert(startLane != 0);
6063#ifdef DEBUG_BESTLANES
6064 if (DEBUG_COND) {
6065 std::cout << " startLaneIsOpposite newStartLane=" << startLane->getID() << "\n";
6066 }
6067#endif
6068 }
6069 }
6070 if (forceRebuild) {
6071 myLastBestLanesEdge = nullptr;
6073 }
6074 if (myBestLanes.size() > 0 && !forceRebuild && myLastBestLanesEdge == &startLane->getEdge()) {
6076#ifdef DEBUG_BESTLANES
6077 if (DEBUG_COND) {
6078 std::cout << " only updateOccupancyAndCurrentBestLane\n";
6079 }
6080#endif
6081 return;
6082 }
6083 if (startLane->getEdge().isInternal()) {
6084 if (myBestLanes.size() == 0 || forceRebuild) {
6085 // rebuilt from previous non-internal lane (may backtrack twice if behind an internal junction)
6086 updateBestLanes(true, startLane->getLogicalPredecessorLane());
6087 }
6088 if (myLastBestLanesInternalLane == startLane && !forceRebuild) {
6089#ifdef DEBUG_BESTLANES
6090 if (DEBUG_COND) {
6091 std::cout << " nothing to do on internal\n";
6092 }
6093#endif
6094 return;
6095 }
6096 // adapt best lanes to fit the current internal edge:
6097 // keep the entries that are reachable from this edge
6098 const MSEdge* nextEdge = startLane->getNextNormal();
6099 assert(!nextEdge->isInternal());
6100 for (std::vector<std::vector<LaneQ> >::iterator it = myBestLanes.begin(); it != myBestLanes.end();) {
6101 std::vector<LaneQ>& lanes = *it;
6102 assert(lanes.size() > 0);
6103 if (&(lanes[0].lane->getEdge()) == nextEdge) {
6104 // keep those lanes which are successors of internal lanes from the edge of startLane
6105 std::vector<LaneQ> oldLanes = lanes;
6106 lanes.clear();
6107 const std::vector<MSLane*>& sourceLanes = startLane->getEdge().getLanes();
6108 for (std::vector<MSLane*>::const_iterator it_source = sourceLanes.begin(); it_source != sourceLanes.end(); ++it_source) {
6109 for (std::vector<LaneQ>::iterator it_lane = oldLanes.begin(); it_lane != oldLanes.end(); ++it_lane) {
6110 if ((*it_source)->getLinkCont()[0]->getLane() == (*it_lane).lane) {
6111 lanes.push_back(*it_lane);
6112 break;
6113 }
6114 }
6115 }
6116 assert(lanes.size() == startLane->getEdge().getLanes().size());
6117 // patch invalid bestLaneOffset and updated myCurrentLaneInBestLanes
6118 for (int i = 0; i < (int)lanes.size(); ++i) {
6119 if (i + lanes[i].bestLaneOffset < 0) {
6120 lanes[i].bestLaneOffset = -i;
6121 }
6122 if (i + lanes[i].bestLaneOffset >= (int)lanes.size()) {
6123 lanes[i].bestLaneOffset = (int)lanes.size() - i - 1;
6124 }
6125 assert(i + lanes[i].bestLaneOffset >= 0);
6126 assert(i + lanes[i].bestLaneOffset < (int)lanes.size());
6127 if (lanes[i].bestContinuations[0] != 0) {
6128 // patch length of bestContinuation to match expectations (only once)
6129 lanes[i].bestContinuations.insert(lanes[i].bestContinuations.begin(), (MSLane*)nullptr);
6130 }
6131 if (startLane->getLinkCont()[0]->getLane() == lanes[i].lane) {
6132 myCurrentLaneInBestLanes = lanes.begin() + i;
6133 }
6134 assert(&(lanes[i].lane->getEdge()) == nextEdge);
6135 }
6136 myLastBestLanesInternalLane = startLane;
6138#ifdef DEBUG_BESTLANES
6139 if (DEBUG_COND) {
6140 std::cout << " updated for internal\n";
6141 }
6142#endif
6143 return;
6144 } else {
6145 // remove passed edges
6146 it = myBestLanes.erase(it);
6147 }
6148 }
6149 assert(false); // should always find the next edge
6150 }
6151 // start rebuilding
6153 myLastBestLanesEdge = &startLane->getEdge();
6155
6156 // get information about the next stop
6157 MSRouteIterator nextStopEdge = myRoute->end();
6158 const MSLane* nextStopLane = nullptr;
6159 double nextStopPos = 0;
6160 if (!myStops.empty()) {
6161 const MSStop& nextStop = myStops.front();
6162 nextStopLane = nextStop.lane;
6163 if (nextStop.isOpposite) {
6164 // target leftmost lane in forward direction
6165 nextStopLane = nextStopLane->getEdge().getOppositeEdge()->getLanes().back();
6166 }
6167 nextStopEdge = nextStop.edge;
6168 nextStopPos = nextStop.pars.startPos;
6169 }
6170 // myArrivalTime = -1 in the context of validating departSpeed with departLane=best
6171 if (myParameter->arrivalLaneProcedure >= ArrivalLaneDefinition::GIVEN && nextStopEdge == myRoute->end() && myArrivalLane >= 0) {
6172 nextStopEdge = (myRoute->end() - 1);
6173 nextStopLane = (*nextStopEdge)->getLanes()[myArrivalLane];
6174 nextStopPos = myArrivalPos;
6175 }
6176 if (nextStopEdge != myRoute->end()) {
6177 // make sure that the "wrong" lanes get a penalty. (penalty needs to be
6178 // large enough to overcome a magic threshold in MSLaneChangeModel::DK2004.cpp:383)
6179 nextStopPos = MAX2(POSITION_EPS, MIN2((double)nextStopPos, (double)(nextStopLane->getLength() - 2 * POSITION_EPS)));
6180 if (nextStopLane->isInternal()) {
6181 // switch to the correct lane before entering the intersection
6182 nextStopPos = (*nextStopEdge)->getLength();
6183 }
6184 }
6185
6186 // go forward along the next lanes; always look past stops to ensure that we
6187 // know where to go once the stop ends
6188 // trains do not have to deal with lane-changing for stops but their best
6189 // lanes lookahead is needed for rail signal control
6190 int seen = 0;
6191 double seenLength = 0;
6192 bool progress = true;
6193 // bestLanes must cover the braking distance even when at the very end of the current lane to avoid unecessary slow down
6194 const double maxBrakeDist = startLane->getLength() + getCarFollowModel().getHeadwayTime() * getMaxSpeed() + getCarFollowModel().brakeGap(getMaxSpeed()) + getVehicleType().getMinGap();
6195 const double lookahead = getLaneChangeModel().getStrategicLookahead();
6196 for (MSRouteIterator ce = myCurrEdge; progress;) {
6197 std::vector<LaneQ> currentLanes;
6198 const std::vector<MSLane*>* allowed = nullptr;
6199 const MSEdge* nextEdge = nullptr;
6200 if (ce != myRoute->end() && ce + 1 != myRoute->end()) {
6201 nextEdge = *(ce + 1);
6202 allowed = (*ce)->allowedLanes(*nextEdge, myType->getVehicleClass());
6203 }
6204 const std::vector<MSLane*>& lanes = (*ce)->getLanes();
6205 for (std::vector<MSLane*>::const_iterator i = lanes.begin(); i != lanes.end(); ++i) {
6206 LaneQ q;
6207 MSLane* cl = *i;
6208 q.lane = cl;
6209 q.bestContinuations.push_back(cl);
6210 q.bestLaneOffset = 0;
6211 q.length = cl->allowsVehicleClass(myType->getVehicleClass()) ? (*ce)->getLength() : 0;
6212 q.currentLength = q.length;
6213 // if all lanes are forbidden (i.e. due to a dynamic closing) we want to express no preference
6214 q.allowsContinuation = allowed == nullptr || std::find(allowed->begin(), allowed->end(), cl) != allowed->end();
6215 q.occupation = 0;
6216 q.nextOccupation = 0;
6217 currentLanes.push_back(q);
6218 }
6219 //
6220 if (nextStopEdge == ce
6221 // already past the stop edge
6222 && !(ce == myCurrEdge && myLane != nullptr && myLane->isInternal())) {
6223 const MSLane* normalStopLane = nextStopLane->getNormalPredecessorLane();
6224 for (std::vector<LaneQ>::iterator q = currentLanes.begin(); q != currentLanes.end(); ++q) {
6225 if (nextStopLane != nullptr && normalStopLane != (*q).lane) {
6226 (*q).allowsContinuation = false;
6227 (*q).length = nextStopPos;
6228 (*q).currentLength = (*q).length;
6229 }
6230 }
6231 }
6232
6233 myBestLanes.push_back(currentLanes);
6234 ++seen;
6235 seenLength += currentLanes[0].lane->getLength();
6236 ++ce;
6237 if (lookahead >= 0) {
6238 progress &= (seen <= 2 || seenLength < lookahead); // custom (but we need to look at least one edge ahead)
6239 } else {
6240 progress &= (seen <= 4 || seenLength < MAX2(maxBrakeDist, 3000.0)); // motorway
6241 progress &= (seen <= 8 || seenLength < MAX2(maxBrakeDist, 200.0) || isRailway(getVClass())); // urban
6242 }
6243 progress &= ce != myRoute->end();
6244 /*
6245 if(progress) {
6246 progress &= (currentLanes.size()!=1||(*ce)->getLanes().size()!=1);
6247 }
6248 */
6249 }
6250
6251 // we are examining the last lane explicitly
6252 if (myBestLanes.size() != 0) {
6253 double bestLength = -1;
6254 // minimum and maximum lane index with best length
6255 int bestThisIndex = 0;
6256 int bestThisMaxIndex = 0;
6257 int index = 0;
6258 std::vector<LaneQ>& last = myBestLanes.back();
6259 for (std::vector<LaneQ>::iterator j = last.begin(); j != last.end(); ++j, ++index) {
6260 if ((*j).length > bestLength) {
6261 bestLength = (*j).length;
6262 bestThisIndex = index;
6263 bestThisMaxIndex = index;
6264 } else if ((*j).length == bestLength) {
6265 bestThisMaxIndex = index;
6266 }
6267 }
6268 index = 0;
6269 bool requiredChangeRightForbidden = false;
6270 int requireChangeToLeftForbidden = -1;
6271 for (std::vector<LaneQ>::iterator j = last.begin(); j != last.end(); ++j, ++index) {
6272 if ((*j).length < bestLength) {
6273 if (abs(bestThisIndex - index) < abs(bestThisMaxIndex - index)) {
6274 (*j).bestLaneOffset = bestThisIndex - index;
6275 } else {
6276 (*j).bestLaneOffset = bestThisMaxIndex - index;
6277 }
6278 if (!(*j).allowsContinuation) {
6279 if ((*j).bestLaneOffset < 0 && (!(*j).lane->allowsChangingRight(getVClass())
6280 || !(*j).lane->getParallelLane(-1, false)->allowsVehicleClass(getVClass())
6281 || requiredChangeRightForbidden)) {
6282 // this lane and all further lanes to the left cannot be used
6283 requiredChangeRightForbidden = true;
6284 (*j).length = 0;
6285 } else if ((*j).bestLaneOffset > 0 && (!(*j).lane->allowsChangingLeft(getVClass())
6286 || !(*j).lane->getParallelLane(1, false)->allowsVehicleClass(getVClass()))) {
6287 // this lane and all previous lanes to the right cannot be used
6288 requireChangeToLeftForbidden = (*j).lane->getIndex();
6289 }
6290 }
6291 }
6292 }
6293 for (int i = requireChangeToLeftForbidden; i >= 0; i--) {
6294 if (last[i].bestLaneOffset > 0) {
6295 last[i].length = 0;
6296 }
6297 }
6298#ifdef DEBUG_BESTLANES
6299 if (DEBUG_COND) {
6300 std::cout << " last edge=" << last.front().lane->getEdge().getID() << " (bestIndex=" << bestThisIndex << " bestMaxIndex=" << bestThisMaxIndex << "):\n";
6301 std::vector<LaneQ>& laneQs = myBestLanes.back();
6302 for (std::vector<LaneQ>::iterator j = laneQs.begin(); j != laneQs.end(); ++j) {
6303 std::cout << " lane=" << (*j).lane->getID() << " length=" << (*j).length << " bestOffset=" << (*j).bestLaneOffset << "\n";
6304 }
6305 }
6306#endif
6307 }
6308 // go backward through the lanes
6309 // track back best lane and compute the best prior lane(s)
6310 for (std::vector<std::vector<LaneQ> >::reverse_iterator i = myBestLanes.rbegin() + 1; i != myBestLanes.rend(); ++i) {
6311 std::vector<LaneQ>& nextLanes = (*(i - 1));
6312 std::vector<LaneQ>& clanes = (*i);
6313 MSEdge* const cE = &clanes[0].lane->getEdge();
6314 int index = 0;
6315 double bestConnectedLength = -1;
6316 double bestLength = -1;
6317 for (const LaneQ& j : nextLanes) {
6318 if (j.lane->isApproachedFrom(cE) && bestConnectedLength < j.length) {
6319 bestConnectedLength = j.length;
6320 }
6321 if (bestLength < j.length) {
6322 bestLength = j.length;
6323 }
6324 }
6325 // compute index of the best lane (highest length and least offset from the best next lane)
6326 int bestThisIndex = 0;
6327 int bestThisMaxIndex = 0;
6328 if (bestConnectedLength > 0) {
6329 index = 0;
6330 for (LaneQ& j : clanes) {
6331 const LaneQ* bestConnectedNext = nullptr;
6332 if (j.allowsContinuation) {
6333 for (const LaneQ& m : nextLanes) {
6334 if ((m.lane->allowsVehicleClass(getVClass()) || m.lane->hadPermissionChanges())
6335 && m.lane->isApproachedFrom(j.lane, getVClass())) {
6336 if (betterContinuation(bestConnectedNext, m)) {
6337 bestConnectedNext = &m;
6338 }
6339 }
6340 }
6341 if (bestConnectedNext != nullptr) {
6342 if (bestConnectedNext->length == bestConnectedLength && abs(bestConnectedNext->bestLaneOffset) < 2) {
6343 j.length += bestLength;
6344 } else {
6345 j.length += bestConnectedNext->length;
6346 }
6347 j.bestLaneOffset = bestConnectedNext->bestLaneOffset;
6348 }
6349 }
6350 if (bestConnectedNext != nullptr && (bestConnectedNext->allowsContinuation || bestConnectedNext->length > 0)) {
6351 copy(bestConnectedNext->bestContinuations.begin(), bestConnectedNext->bestContinuations.end(), back_inserter(j.bestContinuations));
6352 } else {
6353 j.allowsContinuation = false;
6354 }
6355 if (clanes[bestThisIndex].length < j.length
6356 || (clanes[bestThisIndex].length == j.length && abs(clanes[bestThisIndex].bestLaneOffset) > abs(j.bestLaneOffset))
6357 || (clanes[bestThisIndex].length == j.length && abs(clanes[bestThisIndex].bestLaneOffset) == abs(j.bestLaneOffset) &&
6358 nextLinkPriority(clanes[bestThisIndex].bestContinuations) < nextLinkPriority(j.bestContinuations))
6359 ) {
6360 bestThisIndex = index;
6361 bestThisMaxIndex = index;
6362 } else if (clanes[bestThisIndex].length == j.length
6363 && abs(clanes[bestThisIndex].bestLaneOffset) == abs(j.bestLaneOffset)
6364 && nextLinkPriority(clanes[bestThisIndex].bestContinuations) == nextLinkPriority(j.bestContinuations)) {
6365 bestThisMaxIndex = index;
6366 }
6367 index++;
6368 }
6369
6370 //vehicle with elecHybrid device prefers running under an overhead wire
6371 if (getDevice(typeid(MSDevice_ElecHybrid)) != nullptr) {
6372 index = 0;
6373 for (const LaneQ& j : clanes) {
6374 std::string overheadWireSegmentID = MSNet::getInstance()->getStoppingPlaceID(j.lane, j.currentLength / 2., SUMO_TAG_OVERHEAD_WIRE_SEGMENT);
6375 if (overheadWireSegmentID != "") {
6376 bestThisIndex = index;
6377 bestThisMaxIndex = index;
6378 }
6379 index++;
6380 }
6381 }
6382
6383 } else {
6384 // only needed in case of disconnected routes
6385 int bestNextIndex = 0;
6386 int bestDistToNeeded = (int) clanes.size();
6387 index = 0;
6388 for (std::vector<LaneQ>::iterator j = clanes.begin(); j != clanes.end(); ++j, ++index) {
6389 if ((*j).allowsContinuation) {
6390 int nextIndex = 0;
6391 for (std::vector<LaneQ>::const_iterator m = nextLanes.begin(); m != nextLanes.end(); ++m, ++nextIndex) {
6392 if ((*m).lane->isApproachedFrom((*j).lane, getVClass())) {
6393 if (bestDistToNeeded > abs((*m).bestLaneOffset)) {
6394 bestDistToNeeded = abs((*m).bestLaneOffset);
6395 bestThisIndex = index;
6396 bestThisMaxIndex = index;
6397 bestNextIndex = nextIndex;
6398 }
6399 }
6400 }
6401 }
6402 }
6403 clanes[bestThisIndex].length += nextLanes[bestNextIndex].length;
6404 copy(nextLanes[bestNextIndex].bestContinuations.begin(), nextLanes[bestNextIndex].bestContinuations.end(), back_inserter(clanes[bestThisIndex].bestContinuations));
6405
6406 }
6407 // set bestLaneOffset for all lanes
6408 index = 0;
6409 bool requiredChangeRightForbidden = false;
6410 int requireChangeToLeftForbidden = -1;
6411 for (std::vector<LaneQ>::iterator j = clanes.begin(); j != clanes.end(); ++j, ++index) {
6412 if ((*j).length < clanes[bestThisIndex].length
6413 || ((*j).length == clanes[bestThisIndex].length && abs((*j).bestLaneOffset) > abs(clanes[bestThisIndex].bestLaneOffset))
6414 || (nextLinkPriority((*j).bestContinuations)) < nextLinkPriority(clanes[bestThisIndex].bestContinuations)
6415 ) {
6416 if (abs(bestThisIndex - index) < abs(bestThisMaxIndex - index)) {
6417 (*j).bestLaneOffset = bestThisIndex - index;
6418 } else {
6419 (*j).bestLaneOffset = bestThisMaxIndex - index;
6420 }
6421 if ((nextLinkPriority((*j).bestContinuations)) < nextLinkPriority(clanes[bestThisIndex].bestContinuations)) {
6422 // try to move away from the lower-priority lane before it ends
6423 (*j).length = (*j).currentLength;
6424 }
6425 if (!(*j).allowsContinuation) {
6426 if ((*j).bestLaneOffset < 0 && (!(*j).lane->allowsChangingRight(getVClass())
6427 || !(*j).lane->getParallelLane(-1, false)->allowsVehicleClass(getVClass())
6428 || requiredChangeRightForbidden)) {
6429 // this lane and all further lanes to the left cannot be used
6430 requiredChangeRightForbidden = true;
6431 if ((*j).length == (*j).currentLength) {
6432 (*j).length = 0;
6433 }
6434 } else if ((*j).bestLaneOffset > 0 && (!(*j).lane->allowsChangingLeft(getVClass())
6435 || !(*j).lane->getParallelLane(1, false)->allowsVehicleClass(getVClass()))) {
6436 // this lane and all previous lanes to the right cannot be used
6437 requireChangeToLeftForbidden = (*j).lane->getIndex();
6438 }
6439 }
6440 } else {
6441 (*j).bestLaneOffset = 0;
6442 }
6443 }
6444 for (int idx = requireChangeToLeftForbidden; idx >= 0; idx--) {
6445 if (clanes[idx].length == clanes[idx].currentLength) {
6446 clanes[idx].length = 0;
6447 };
6448 }
6449
6450 //vehicle with elecHybrid device prefers running under an overhead wire
6451 if (static_cast<MSDevice_ElecHybrid*>(getDevice(typeid(MSDevice_ElecHybrid))) != 0) {
6452 index = 0;
6453 std::string overheadWireID = MSNet::getInstance()->getStoppingPlaceID(clanes[bestThisIndex].lane, (clanes[bestThisIndex].currentLength) / 2, SUMO_TAG_OVERHEAD_WIRE_SEGMENT);
6454 if (overheadWireID != "") {
6455 for (std::vector<LaneQ>::iterator j = clanes.begin(); j != clanes.end(); ++j, ++index) {
6456 (*j).bestLaneOffset = bestThisIndex - index;
6457 }
6458 }
6459 }
6460
6461#ifdef DEBUG_BESTLANES
6462 if (DEBUG_COND) {
6463 std::cout << " edge=" << cE->getID() << " (bestIndex=" << bestThisIndex << " bestMaxIndex=" << bestThisMaxIndex << "):\n";
6464 std::vector<LaneQ>& laneQs = clanes;
6465 for (std::vector<LaneQ>::iterator j = laneQs.begin(); j != laneQs.end(); ++j) {
6466 std::cout << " lane=" << (*j).lane->getID() << " length=" << (*j).length << " bestOffset=" << (*j).bestLaneOffset << " allowCont=" << (*j).allowsContinuation << "\n";
6467 }
6468 }
6469#endif
6470
6471 }
6472 if (myBestLanes.front().front().lane->isInternal()) {
6473 // route starts on an internal lane
6474 if (myLane != nullptr) {
6475 startLane = myLane;
6476 } else {
6477 // vehicle not yet departed
6478 startLane = myBestLanes.front().front().lane;
6479 }
6480 }
6482#ifdef DEBUG_BESTLANES
6483 if (DEBUG_COND) {
6484 std::cout << SIMTIME << " veh=" << getID() << " bestCont=" << toString(getBestLanesContinuation()) << "\n";
6485 }
6486#endif
6487}
6488
6489void
6491 if (myLane != nullptr) {
6493 }
6494}
6495
6496bool
6497MSVehicle::betterContinuation(const LaneQ* bestConnectedNext, const LaneQ& m) const {
6498 if (bestConnectedNext == nullptr) {
6499 return true;
6500 } else if (m.lane->getBidiLane() != nullptr && bestConnectedNext->lane->getBidiLane() == nullptr) {
6501 return false;
6502 } else if (bestConnectedNext->lane->getBidiLane() != nullptr && m.lane->getBidiLane() == nullptr) {
6503 return true;
6504 } else if (bestConnectedNext->length < m.length) {
6505 return true;
6506 } else if (bestConnectedNext->length == m.length) {
6507 if (abs(bestConnectedNext->bestLaneOffset) > abs(m.bestLaneOffset)) {
6508 return true;
6509 }
6510 const double contRight = getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_CONTRIGHT, 1);
6511 if (contRight < 1
6512 // if we don't check for adjacency, the rightmost line will get
6513 // multiple chances to be better which leads to an uninituitve distribution
6514 && (m.lane->getIndex() - bestConnectedNext->lane->getIndex()) == 1
6515 && RandHelper::rand(getRNG()) > contRight) {
6516 return true;
6517 }
6518 }
6519 return false;
6520}
6521
6522
6523int
6524MSVehicle::nextLinkPriority(const std::vector<MSLane*>& conts) {
6525 if (conts.size() < 2) {
6526 return -1;
6527 } else {
6528 const MSLink* const link = conts[0]->getLinkTo(conts[1]);
6529 if (link != nullptr) {
6530 return link->havePriority() ? 1 : 0;
6531 } else {
6532 // disconnected route
6533 return -1;
6534 }
6535 }
6536}
6537
6538
6539void
6541 std::vector<LaneQ>& currLanes = *myBestLanes.begin();
6542 std::vector<LaneQ>::iterator i;
6543#ifdef _DEBUG
6544 bool found = false;
6545#endif
6546 for (i = currLanes.begin(); i != currLanes.end(); ++i) {
6547 double nextOccupation = 0;
6548 for (std::vector<MSLane*>::const_iterator j = (*i).bestContinuations.begin() + 1; j != (*i).bestContinuations.end(); ++j) {
6549 nextOccupation += (*j)->getBruttoVehLenSum();
6550 }
6551 (*i).nextOccupation = nextOccupation;
6552#ifdef DEBUG_BESTLANES
6553 if (DEBUG_COND) {
6554 std::cout << " lane=" << (*i).lane->getID() << " nextOccupation=" << nextOccupation << "\n";
6555 }
6556#endif
6557 if ((*i).lane == startLane) {
6559#ifdef _DEBUG
6560 found = true;
6561#endif
6562 }
6563 }
6564#ifdef _DEBUG
6565 assert(found || startLane->isInternal());
6566#endif
6567}
6568
6569
6570const std::vector<MSLane*>&
6572 if (myBestLanes.empty() || myBestLanes[0].empty()) {
6573 return myEmptyLaneVector;
6574 }
6575 return (*myCurrentLaneInBestLanes).bestContinuations;
6576}
6577
6578
6579const std::vector<MSLane*>&
6581 const MSLane* lane = l;
6582 // XXX: shouldn't this be a "while" to cover more than one internal lane? (Leo) Refs. #2575
6583 if (lane->getEdge().isInternal()) {
6584 // internal edges are not kept inside the bestLanes structure
6585 lane = lane->getLinkCont()[0]->getLane();
6586 }
6587 if (myBestLanes.size() == 0) {
6588 return myEmptyLaneVector;
6589 }
6590 for (std::vector<LaneQ>::const_iterator i = myBestLanes[0].begin(); i != myBestLanes[0].end(); ++i) {
6591 if ((*i).lane == lane) {
6592 return (*i).bestContinuations;
6593 }
6594 }
6595 return myEmptyLaneVector;
6596}
6597
6598const std::vector<const MSLane*>
6599MSVehicle::getUpcomingLanesUntil(double distance) const {
6600 std::vector<const MSLane*> lanes;
6601
6602 if (distance <= 0. || hasArrived()) {
6603 // WRITE_WARNINGF(TL("MSVehicle::getUpcomingLanesUntil(): distance ('%') should be greater than 0."), distance);
6604 return lanes;
6605 }
6606
6607 if (!myLaneChangeModel->isOpposite()) {
6608 distance += getPositionOnLane();
6609 } else {
6610 distance += myLane->getOppositePos(getPositionOnLane());
6611 }
6613 while (lane->isInternal() && (distance > 0.)) { // include initial internal lanes
6614 lanes.insert(lanes.end(), lane);
6615 distance -= lane->getLength();
6616 lane = lane->getLinkCont().front()->getViaLaneOrLane();
6617 }
6618
6619 const std::vector<MSLane*>& contLanes = getBestLanesContinuation();
6620 if (contLanes.empty()) {
6621 return lanes;
6622 }
6623 auto contLanesIt = contLanes.begin();
6624 MSRouteIterator routeIt = myCurrEdge; // keep track of covered edges in myRoute
6625 while (distance > 0.) {
6626 MSLane* l = nullptr;
6627 if (contLanesIt != contLanes.end()) {
6628 l = *contLanesIt;
6629 if (l != nullptr) {
6630 assert(l->getEdge().getID() == (*routeIt)->getLanes().front()->getEdge().getID());
6631 }
6632 ++contLanesIt;
6633 if (l != nullptr || myLane->isInternal()) {
6634 ++routeIt;
6635 }
6636 if (l == nullptr) {
6637 continue;
6638 }
6639 } else if (routeIt != myRoute->end()) { // bestLanes didn't get us far enough
6640 // choose left-most lane as default (avoid sidewalks, bike lanes etc)
6641 l = (*routeIt)->getLanes().back();
6642 ++routeIt;
6643 } else { // the search distance goes beyond our route
6644 break;
6645 }
6646
6647 assert(l != nullptr);
6648
6649 // insert internal lanes if applicable
6650 const MSLane* internalLane = lanes.size() > 0 ? lanes.back()->getInternalFollowingLane(l) : nullptr;
6651 while ((internalLane != nullptr) && internalLane->isInternal() && (distance > 0.)) {
6652 lanes.insert(lanes.end(), internalLane);
6653 distance -= internalLane->getLength();
6654 internalLane = internalLane->getLinkCont().front()->getViaLaneOrLane();
6655 }
6656 if (distance <= 0.) {
6657 break;
6658 }
6659
6660 lanes.insert(lanes.end(), l);
6661 distance -= l->getLength();
6662 }
6663
6664 return lanes;
6665}
6666
6667const std::vector<const MSLane*>
6668MSVehicle::getPastLanesUntil(double distance) const {
6669 std::vector<const MSLane*> lanes;
6670
6671 if (distance <= 0.) {
6672 // WRITE_WARNINGF(TL("MSVehicle::getPastLanesUntil(): distance ('%') should be greater than 0."), distance);
6673 return lanes;
6674 }
6675
6676 MSRouteIterator routeIt = myCurrEdge;
6677 if (!myLaneChangeModel->isOpposite()) {
6678 distance += myLane->getLength() - getPositionOnLane();
6679 } else {
6681 }
6683 while (lane->isInternal() && (distance > 0.)) { // include initial internal lanes
6684 lanes.insert(lanes.end(), lane);
6685 distance -= lane->getLength();
6686 lane = lane->getLogicalPredecessorLane();
6687 }
6688
6689 while (distance > 0.) {
6690 // choose left-most lane as default (avoid sidewalks, bike lanes etc)
6691 MSLane* l = (*routeIt)->getLanes().back();
6692
6693 // insert internal lanes if applicable
6694 const MSEdge* internalEdge = lanes.size() > 0 ? (*routeIt)->getInternalFollowingEdge(&(lanes.back()->getEdge()), getVClass()) : nullptr;
6695 const MSLane* internalLane = internalEdge != nullptr ? internalEdge->getLanes().front() : nullptr;
6696 std::vector<const MSLane*> internalLanes;
6697 while ((internalLane != nullptr) && internalLane->isInternal()) { // collect all internal successor lanes
6698 internalLanes.insert(internalLanes.begin(), internalLane);
6699 internalLane = internalLane->getLinkCont().front()->getViaLaneOrLane();
6700 }
6701 for (auto it = internalLanes.begin(); (it != internalLanes.end()) && (distance > 0.); ++it) { // check remaining distance in correct order
6702 lanes.insert(lanes.end(), *it);
6703 distance -= (*it)->getLength();
6704 }
6705 if (distance <= 0.) {
6706 break;
6707 }
6708
6709 lanes.insert(lanes.end(), l);
6710 distance -= l->getLength();
6711
6712 // NOTE: we're going backwards with the (bi-directional) Iterator
6713 // TODO: consider make reverse_iterator() when moving on to C++14 or later
6714 if (routeIt != myRoute->begin()) {
6715 --routeIt;
6716 } else { // we went backwards to begin() and already processed the first and final element
6717 break;
6718 }
6719 }
6720
6721 return lanes;
6722}
6723
6724
6725const std::vector<MSLane*>
6727 const std::vector<const MSLane*> routeLanes = getPastLanesUntil(myLane->getMaximumBrakeDist());
6728 std::vector<MSLane*> result;
6729 for (const MSLane* lane : routeLanes) {
6730 MSLane* opposite = lane->getOpposite();
6731 if (opposite != nullptr) {
6732 result.push_back(opposite);
6733 } else {
6734 break;
6735 }
6736 }
6737 return result;
6738}
6739
6740
6741int
6743 if (myBestLanes.empty() || myBestLanes[0].empty()) {
6744 return 0;
6745 } else {
6746 return (*myCurrentLaneInBestLanes).bestLaneOffset;
6747 }
6748}
6749
6750double
6752 if (myBestLanes.empty() || myBestLanes[0].empty()) {
6753 return -1;
6754 } else {
6755 return (*myCurrentLaneInBestLanes).length;
6756 }
6757}
6758
6759
6760
6761void
6762MSVehicle::adaptBestLanesOccupation(int laneIndex, double density) {
6763 std::vector<MSVehicle::LaneQ>& preb = myBestLanes.front();
6764 assert(laneIndex < (int)preb.size());
6765 preb[laneIndex].occupation = density + preb[laneIndex].nextOccupation;
6766}
6767
6768
6769void
6775
6776std::pair<const MSLane*, double>
6777MSVehicle::getLanePosAfterDist(double distance) const {
6778 if (distance == 0) {
6779 return std::make_pair(myLane, getPositionOnLane());
6780 }
6781 const std::vector<const MSLane*> lanes = getUpcomingLanesUntil(distance);
6782 distance += getPositionOnLane();
6783 for (const MSLane* lane : lanes) {
6784 if (lane->getLength() > distance) {
6785 return std::make_pair(lane, distance);
6786 }
6787 distance -= lane->getLength();
6788 }
6789 return std::make_pair(nullptr, -1);
6790}
6791
6792
6793double
6794MSVehicle::getDistanceToPosition(double destPos, const MSLane* destLane) const {
6795 if (isOnRoad() && destLane != nullptr) {
6796 return myRoute->getDistanceBetween(getPositionOnLane(), destPos, myLane, destLane);
6797 }
6798 return std::numeric_limits<double>::max();
6799}
6800
6801
6802std::pair<const MSVehicle* const, double>
6803MSVehicle::getLeader(double dist, bool considerCrossingFoes) const {
6804 if (myLane == nullptr) {
6805 return std::make_pair(static_cast<const MSVehicle*>(nullptr), -1);
6806 }
6807 if (dist == 0) {
6809 }
6810 const MSVehicle* lead = nullptr;
6811 const MSLane* lane = myLane; // ensure lane does not change between getVehiclesSecure and releaseVehicles;
6812 const MSLane::VehCont& vehs = lane->getVehiclesSecure();
6813 // vehicle might be outside the road network
6814 MSLane::VehCont::const_iterator it = std::find(vehs.begin(), vehs.end(), this);
6815 if (it != vehs.end() && it + 1 != vehs.end()) {
6816 lead = *(it + 1);
6817 }
6818 if (lead != nullptr) {
6819 std::pair<const MSVehicle* const, double> result(
6820 lead, lead->getBackPositionOnLane(myLane) - getPositionOnLane() - getVehicleType().getMinGap());
6821 lane->releaseVehicles();
6822 return result;
6823 }
6824 const double seen = myLane->getLength() - getPositionOnLane();
6825 const std::vector<MSLane*>& bestLaneConts = getBestLanesContinuation(myLane);
6826 std::pair<const MSVehicle* const, double> result = myLane->getLeaderOnConsecutive(dist, seen, getSpeed(), *this, bestLaneConts, considerCrossingFoes);
6827 lane->releaseVehicles();
6828 return result;
6829}
6830
6831
6832std::pair<const MSVehicle* const, double>
6833MSVehicle::getFollower(double dist) const {
6834 if (myLane == nullptr) {
6835 return std::make_pair(static_cast<const MSVehicle*>(nullptr), -1);
6836 }
6837 if (dist == 0) {
6838 dist = getCarFollowModel().brakeGap(myLane->getEdge().getSpeedLimit() * 2, 4.5, 0);
6839 }
6841}
6842
6843
6844double
6846 // calling getLeader with 0 would induce a dist calculation but we only want to look for the leaders on the current lane
6847 std::pair<const MSVehicle* const, double> leaderInfo = getLeader(-1);
6848 if (leaderInfo.first == nullptr || getSpeed() == 0) {
6849 return -1;
6850 }
6851 return (leaderInfo.second + getVehicleType().getMinGap()) / getSpeed();
6852}
6853
6854
6855void
6857 MSBaseVehicle::addTransportable(transportable);
6858 if (myStops.size() > 0 && myStops.front().reached) {
6859 if (transportable->isPerson()) {
6860 if (myStops.front().triggered && myStops.front().numExpectedPerson > 0) {
6861 myStops.front().numExpectedPerson -= (int)myStops.front().pars.awaitedPersons.count(transportable->getID());
6862 }
6863 } else {
6864 if (myStops.front().pars.containerTriggered && myStops.front().numExpectedContainer > 0) {
6865 myStops.front().numExpectedContainer -= (int)myStops.front().pars.awaitedContainers.count(transportable->getID());
6866 }
6867 }
6868 }
6869}
6870
6871
6872void
6875 int state = myLaneChangeModel->getOwnState();
6876 // do not set blinker for sublane changes or when blocked from changing to the right
6877 const bool blinkerManoeuvre = (((state & LCA_SUBLANE) == 0) && (
6878 (state & LCA_KEEPRIGHT) == 0 || (state & LCA_BLOCKED) == 0));
6882 // lane indices increase from left to right
6883 std::swap(left, right);
6884 }
6885 if ((state & LCA_LEFT) != 0 && blinkerManoeuvre) {
6886 switchOnSignal(left);
6887 } else if ((state & LCA_RIGHT) != 0 && blinkerManoeuvre) {
6888 switchOnSignal(right);
6889 } else if (myLaneChangeModel->isChangingLanes()) {
6891 switchOnSignal(left);
6892 } else {
6893 switchOnSignal(right);
6894 }
6895 } else {
6896 const MSLane* lane = getLane();
6897 std::vector<MSLink*>::const_iterator link = MSLane::succLinkSec(*this, 1, *lane, getBestLanesContinuation());
6898 if (link != lane->getLinkCont().end() && lane->getLength() - getPositionOnLane() < lane->getVehicleMaxSpeed(this) * (double) 7.) {
6899 switch ((*link)->getDirection()) {
6904 break;
6908 break;
6909 default:
6910 break;
6911 }
6912 }
6913 }
6914 // stopping related signals
6915 if (hasStops()
6916 && (myStops.begin()->reached ||
6918 && myStopDist < getCarFollowModel().brakeGap(myLane->getVehicleMaxSpeed(this), getCarFollowModel().getMaxDecel(), 3)))) {
6919 if (myStops.begin()->lane->getIndex() > 0 && myStops.begin()->lane->getParallelLane(-1)->allowsVehicleClass(getVClass())) {
6920 // not stopping on the right. Activate emergency blinkers
6922 } else if (!myStops.begin()->reached && (myStops.begin()->pars.parking == ParkingType::OFFROAD)) {
6923 // signal upcoming parking stop on the current lane when within braking distance (~2 seconds before braking)
6925 }
6926 }
6927 if (myInfluencer != nullptr && myInfluencer->getSignals() >= 0) {
6929 myInfluencer->setSignals(-1); // overwrite computed signals only once
6930 }
6931}
6932
6933void
6935
6936 //TODO look if timestep ist SIMSTEP
6937 if (currentTime % 1000 == 0) {
6940 } else {
6942 }
6943 }
6944}
6945
6946
6947int
6949 return myLane == nullptr ? -1 : myLane->getIndex();
6950}
6951
6952
6953void
6954MSVehicle::setTentativeLaneAndPosition(MSLane* lane, double pos, double posLat) {
6955 myLane = lane;
6956 myState.myPos = pos;
6957 myState.myPosLat = posLat;
6959}
6960
6961
6962double
6964 return myState.myPosLat + 0.5 * myLane->getWidth() - 0.5 * getVehicleType().getWidth();
6965}
6966
6967
6968double
6970 return myState.myPosLat + 0.5 * myLane->getWidth() + 0.5 * getVehicleType().getWidth();
6971}
6972
6973
6974double
6976 return myState.myPosLat + 0.5 * lane->getWidth() - 0.5 * getVehicleType().getWidth();
6977}
6978
6979
6980double
6982 return myState.myPosLat + 0.5 * lane->getWidth() + 0.5 * getVehicleType().getWidth();
6983}
6984
6985
6986double
6988 return getCenterOnEdge(lane) - 0.5 * getVehicleType().getWidth();
6989}
6990
6991
6992double
6994 return getCenterOnEdge(lane) + 0.5 * getVehicleType().getWidth();
6995}
6996
6997
6998double
7000 if (lane == nullptr || &lane->getEdge() == &myLane->getEdge()) {
7002 } else if (lane == myLaneChangeModel->getShadowLane()) {
7003 if (myLaneChangeModel->isOpposite() && &lane->getEdge() != &myLane->getEdge()) {
7004 return lane->getRightSideOnEdge() + lane->getWidth() - myState.myPosLat + 0.5 * myLane->getWidth();
7005 }
7007 return lane->getRightSideOnEdge() + lane->getWidth() + myState.myPosLat + 0.5 * myLane->getWidth();
7008 } else {
7009 return lane->getRightSideOnEdge() - myLane->getWidth() + myState.myPosLat + 0.5 * myLane->getWidth();
7010 }
7011 } else if (lane == myLane->getBidiLane()) {
7012 return lane->getRightSideOnEdge() - myState.myPosLat + 0.5 * lane->getWidth();
7013 } else {
7014 assert(myFurtherLanes.size() == myFurtherLanesPosLat.size());
7015 for (int i = 0; i < (int)myFurtherLanes.size(); ++i) {
7016 if (myFurtherLanes[i] == lane) {
7017#ifdef DEBUG_FURTHER
7018 if (DEBUG_COND) std::cout << " getCenterOnEdge veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " furtherLat=" << myFurtherLanesPosLat[i]
7019 << " result=" << lane->getRightSideOnEdge() + myFurtherLanesPosLat[i] + 0.5 * lane->getWidth()
7020 << "\n";
7021#endif
7022 return lane->getRightSideOnEdge() + myFurtherLanesPosLat[i] + 0.5 * lane->getWidth();
7023 } else if (myFurtherLanes[i]->getBidiLane() == lane) {
7024#ifdef DEBUG_FURTHER
7025 if (DEBUG_COND) std::cout << " getCenterOnEdge veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " furtherLat(bidi)=" << myFurtherLanesPosLat[i]
7026 << " result=" << lane->getRightSideOnEdge() + myFurtherLanesPosLat[i] + 0.5 * lane->getWidth()
7027 << "\n";
7028#endif
7029 return lane->getRightSideOnEdge() - myFurtherLanesPosLat[i] + 0.5 * lane->getWidth();
7030 }
7031 }
7032 //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myShadowFurtherLanes=" << toString(myLaneChangeModel->getShadowFurtherLanes()) << "\n";
7033 const std::vector<MSLane*>& shadowFurther = myLaneChangeModel->getShadowFurtherLanes();
7034 for (int i = 0; i < (int)shadowFurther.size(); ++i) {
7035 //if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
7036 if (shadowFurther[i] == lane) {
7037 assert(myLaneChangeModel->getShadowLane() != 0);
7038 return (lane->getRightSideOnEdge() + myLaneChangeModel->getShadowFurtherLanesPosLat()[i] + 0.5 * lane->getWidth()
7040 } else if (shadowFurther[i]->getBidiLane() == lane) {
7041 assert(myLaneChangeModel->getShadowLane() != 0);
7042 return (lane->getRightSideOnEdge() - myLaneChangeModel->getShadowFurtherLanesPosLat()[i] + 0.5 * lane->getWidth()
7044 }
7045 }
7046 assert(false);
7047 throw ProcessError("Request lateral pos of vehicle '" + getID() + "' for invalid lane '" + Named::getIDSecure(lane) + "'");
7048 }
7049}
7050
7051
7052double
7054 assert(lane != 0);
7055 if (&lane->getEdge() == &myLane->getEdge()) {
7056 return myLane->getRightSideOnEdge() - lane->getRightSideOnEdge();
7057 } else if (myLane->getParallelOpposite() == lane) {
7058 return (myLane->getWidth() + lane->getWidth()) * 0.5 - 2 * getLateralPositionOnLane();
7059 } else if (myLane->getBidiLane() == lane) {
7060 return -2 * getLateralPositionOnLane();
7061 } else {
7062 // Check whether the lane is a further lane for the vehicle
7063 for (int i = 0; i < (int)myFurtherLanes.size(); ++i) {
7064 if (myFurtherLanes[i] == lane) {
7065#ifdef DEBUG_FURTHER
7066 if (DEBUG_COND) {
7067 std::cout << " getLatOffset veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " posLat=" << myState.myPosLat << " furtherLat=" << myFurtherLanesPosLat[i] << "\n";
7068 }
7069#endif
7071 } else if (myFurtherLanes[i]->getBidiLane() == lane) {
7072#ifdef DEBUG_FURTHER
7073 if (DEBUG_COND) {
7074 std::cout << " getLatOffset veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " posLat=" << myState.myPosLat << " furtherBidiLat=" << myFurtherLanesPosLat[i] << "\n";
7075 }
7076#endif
7077 return -2 * (myFurtherLanesPosLat[i] - myState.myPosLat);
7078 }
7079 }
7080#ifdef DEBUG_FURTHER
7081 if (DEBUG_COND) {
7082 std::cout << SIMTIME << " veh=" << getID() << " myShadowFurtherLanes=" << toString(myLaneChangeModel->getShadowFurtherLanes()) << "\n";
7083 }
7084#endif
7085 // Check whether the lane is a "shadow further lane" for the vehicle
7086 const std::vector<MSLane*>& shadowFurther = myLaneChangeModel->getShadowFurtherLanes();
7087 for (int i = 0; i < (int)shadowFurther.size(); ++i) {
7088 if (shadowFurther[i] == lane) {
7089#ifdef DEBUG_FURTHER
7090 if (DEBUG_COND) std::cout << " getLatOffset veh=" << getID()
7091 << " shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane())
7092 << " lane=" << lane->getID()
7093 << " i=" << i
7094 << " posLat=" << myState.myPosLat
7095 << " shadowPosLat=" << getLatOffset(myLaneChangeModel->getShadowLane())
7096 << " shadowFurtherLat=" << myLaneChangeModel->getShadowFurtherLanesPosLat()[i]
7097 << "\n";
7098#endif
7100 } else if (shadowFurther[i]->getBidiLane() == lane) {
7101#ifdef DEBUG_FURTHER
7102 if (DEBUG_COND) {
7103 std::cout << " getLatOffset veh=" << getID() << " shadowbidilane=" << lane->getID() << " i=" << i << " posLat=" << myState.myPosLat << " furtherBidiLat=" << myFurtherLanesPosLat[i] << "\n";
7104 }
7105#endif
7107 }
7108 }
7109 // Check whether the vehicle issued a maneuverReservation on the lane.
7110 const std::vector<MSLane*>& furtherTargets = myLaneChangeModel->getFurtherTargetLanes();
7111 for (int i = 0; i < (int)myFurtherLanes.size(); ++i) {
7112 // Further target lanes are just neighboring lanes of the vehicle's further lanes, @see MSAbstractLaneChangeModel::updateTargetLane()
7113 MSLane* targetLane = furtherTargets[i];
7114 if (targetLane == lane) {
7115 const double targetDir = myLaneChangeModel->getManeuverDist() < 0 ? -1. : 1.;
7116 const double latOffset = myFurtherLanesPosLat[i] - myState.myPosLat + targetDir * 0.5 * (myFurtherLanes[i]->getWidth() + targetLane->getWidth());
7117#ifdef DEBUG_TARGET_LANE
7118 if (DEBUG_COND) {
7119 std::cout << " getLatOffset veh=" << getID()
7120 << " wrt targetLane=" << Named::getIDSecure(myLaneChangeModel->getTargetLane())
7121 << "\n i=" << i
7122 << " posLat=" << myState.myPosLat
7123 << " furtherPosLat=" << myFurtherLanesPosLat[i]
7124 << " maneuverDist=" << myLaneChangeModel->getManeuverDist()
7125 << " targetDir=" << targetDir
7126 << " latOffset=" << latOffset
7127 << std::endl;
7128 }
7129#endif
7130 return latOffset;
7131 } else if (targetLane != nullptr && targetLane->getBidiLane() == lane) {
7132 const double targetDir = myLaneChangeModel->getManeuverDist() < 0 ? -1. : 1.;
7133 const double latOffset = myFurtherLanesPosLat[i] - myState.myPosLat + targetDir * 0.5 * (myFurtherLanes[i]->getWidth() + targetLane->getWidth());
7134#ifdef DEBUG_FURTHER
7135 if (DEBUG_COND) {
7136 std::cout << " getLatOffset veh=" << getID() << " furthertargetbidilane=" << lane->getID() << " i=" << i << " posLat=" << myState.myPosLat << " furtherBidiLat=" << myFurtherLanesPosLat[i] << "\n";
7137 }
7138#endif
7139 return -2 * latOffset;
7140 }
7141 }
7142 assert(false);
7143 throw ProcessError("Request lateral offset of vehicle '" + getID() + "' for invalid lane '" + Named::getIDSecure(lane) + "'");
7144 }
7145}
7146
7147
7148double
7149MSVehicle::lateralDistanceToLane(const int offset) const {
7150 // compute the distance when changing to the neighboring lane
7151 // (ensure we do not lap into the line behind neighLane since there might be unseen blockers)
7152 assert(offset == 0 || offset == 1 || offset == -1);
7153 assert(myLane != nullptr);
7154 assert(myLane->getParallelLane(offset) != nullptr || myLane->getParallelOpposite() != nullptr);
7155 const double halfCurrentLaneWidth = 0.5 * myLane->getWidth();
7156 const double halfVehWidth = 0.5 * (getWidth() + NUMERICAL_EPS);
7157 const double latPos = getLateralPositionOnLane();
7158 const double oppositeSign = getLaneChangeModel().isOpposite() ? -1 : 1;
7159 double leftLimit = halfCurrentLaneWidth - halfVehWidth - oppositeSign * latPos;
7160 double rightLimit = -halfCurrentLaneWidth + halfVehWidth - oppositeSign * latPos;
7161 double latLaneDist = 0; // minimum distance to move the vehicle fully onto the new lane
7162 if (offset == 0) {
7163 if (latPos + halfVehWidth > halfCurrentLaneWidth) {
7164 // correct overlapping left
7165 latLaneDist = halfCurrentLaneWidth - latPos - halfVehWidth;
7166 } else if (latPos - halfVehWidth < -halfCurrentLaneWidth) {
7167 // correct overlapping right
7168 latLaneDist = -halfCurrentLaneWidth - latPos + halfVehWidth;
7169 }
7170 latLaneDist *= oppositeSign;
7171 } else if (offset == -1) {
7172 latLaneDist = rightLimit - (getWidth() + NUMERICAL_EPS);
7173 } else if (offset == 1) {
7174 latLaneDist = leftLimit + (getWidth() + NUMERICAL_EPS);
7175 }
7176#ifdef DEBUG_ACTIONSTEPS
7177 if (DEBUG_COND) {
7178 std::cout << SIMTIME
7179 << " veh=" << getID()
7180 << " halfCurrentLaneWidth=" << halfCurrentLaneWidth
7181 << " halfVehWidth=" << halfVehWidth
7182 << " latPos=" << latPos
7183 << " latLaneDist=" << latLaneDist
7184 << " leftLimit=" << leftLimit
7185 << " rightLimit=" << rightLimit
7186 << "\n";
7187 }
7188#endif
7189 return latLaneDist;
7190}
7191
7192
7193double
7194MSVehicle::getLateralOverlap(double posLat, const MSLane* lane) const {
7195 return (fabs(posLat) + 0.5 * getVehicleType().getWidth()
7196 - 0.5 * lane->getWidth());
7197}
7198
7199double
7203
7204double
7208
7209
7210void
7212 for (const DriveProcessItem& dpi : lfLinks) {
7213 if (dpi.myLink != nullptr) {
7214 dpi.myLink->removeApproaching(this);
7215 }
7216 }
7217 // unregister on all shadow links
7219}
7220
7221
7222bool
7223MSVehicle::unsafeLinkAhead(const MSLane* lane, double zipperDist) const {
7224 // the following links are unsafe:
7225 // - zipper links if they are close enough and have approaching vehicles in the relevant time range
7226 // - unprioritized links if the vehicle is currently approaching a prioritzed link and unable to stop in time
7227 double seen = myLane->getLength() - getPositionOnLane();
7228 const double dist = MAX2(zipperDist, getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), 0));
7229 if (seen < dist) {
7230 const std::vector<MSLane*>& bestLaneConts = getBestLanesContinuation(lane);
7231 int view = 1;
7232 std::vector<MSLink*>::const_iterator link = MSLane::succLinkSec(*this, view, *lane, bestLaneConts);
7233 DriveItemVector::const_iterator di = myLFLinkLanes.begin();
7234 while (!lane->isLinkEnd(link) && seen <= dist) {
7235 if ((!lane->isInternal()
7236 && (((*link)->getState() == LINKSTATE_ZIPPER && seen < (*link)->getFoeVisibilityDistance())
7237 || !(*link)->havePriority()))
7238 || (lane->isInternal() && zipperDist > 0)) {
7239 // find the drive item corresponding to this link
7240 bool found = false;
7241 while (di != myLFLinkLanes.end() && !found) {
7242 if ((*di).myLink != nullptr) {
7243 const MSLane* diPredLane = (*di).myLink->getLaneBefore();
7244 if (diPredLane != nullptr) {
7245 if (&diPredLane->getEdge() == &lane->getEdge()) {
7246 found = true;
7247 }
7248 }
7249 }
7250 if (!found) {
7251 di++;
7252 }
7253 }
7254 if (found) {
7255 const SUMOTime leaveTime = (*link)->getLeaveTime((*di).myArrivalTime, (*di).myArrivalSpeed,
7256 (*di).getLeaveSpeed(), getVehicleType().getLength());
7257 const MSLink* entry = (*link)->getCorrespondingEntryLink();
7258 //if (DEBUG_COND) {
7259 // std::cout << SIMTIME << " veh=" << getID() << " changeTo=" << Named::getIDSecure(bestLaneConts.front()) << " linkState=" << toString((*link)->getState()) << " seen=" << seen << " dist=" << dist << " zipperDist=" << zipperDist << " aT=" << STEPS2TIME((*di).myArrivalTime) << " lT=" << STEPS2TIME(leaveTime) << "\n";
7260 //}
7261 if (entry->hasApproachingFoe((*di).myArrivalTime, leaveTime, (*di).myArrivalSpeed, getCarFollowModel().getMaxDecel())) {
7262 //std::cout << SIMTIME << " veh=" << getID() << " aborting changeTo=" << Named::getIDSecure(bestLaneConts.front()) << " linkState=" << toString((*link)->getState()) << " seen=" << seen << " dist=" << dist << "\n";
7263 return true;
7264 }
7265 }
7266 // no drive item is found if the vehicle aborts its request within dist
7267 }
7268 lane = (*link)->getViaLaneOrLane();
7269 if (!lane->getEdge().isInternal()) {
7270 view++;
7271 }
7272 seen += lane->getLength();
7273 link = MSLane::succLinkSec(*this, view, *lane, bestLaneConts);
7274 }
7275 }
7276 return false;
7277}
7278
7279
7281MSVehicle::getBoundingBox(double offset) const {
7282 PositionVector centerLine;
7283 Position pos = getPosition();
7284 centerLine.push_back(pos);
7285 switch (myType->getGuiShape()) {
7292 for (MSLane* lane : myFurtherLanes) {
7293 centerLine.push_back(lane->getShape().back());
7294 }
7295 break;
7296 }
7297 default:
7298 break;
7299 }
7300 double l = getLength();
7301 Position backPos = getBackPosition();
7302 if (pos.distanceTo2D(backPos) > l + NUMERICAL_EPS) {
7303 // getBackPosition may not match the visual back in networks without internal lanes
7304 double a = getAngle() + M_PI; // angle pointing backwards
7305 backPos = pos + Position(l * cos(a), l * sin(a));
7306 }
7307 centerLine.push_back(backPos);
7308 if (offset != 0) {
7309 centerLine.extrapolate2D(offset);
7310 }
7311 PositionVector result = centerLine;
7312 result.move2side(MAX2(0.0, 0.5 * myType->getWidth() + offset));
7313 centerLine.move2side(MIN2(0.0, -0.5 * myType->getWidth() - offset));
7314 result.append(centerLine.reverse(), POSITION_EPS);
7315 return result;
7316}
7317
7318
7320MSVehicle::getBoundingPoly(double offset) const {
7321 switch (myType->getGuiShape()) {
7327 // box with corners cut off
7328 PositionVector result;
7329 PositionVector centerLine;
7330 centerLine.push_back(getPosition());
7331 centerLine.push_back(getBackPosition());
7332 if (offset != 0) {
7333 centerLine.extrapolate2D(offset);
7334 }
7335 PositionVector line1 = centerLine;
7336 PositionVector line2 = centerLine;
7337 line1.move2side(MAX2(0.0, 0.3 * myType->getWidth() + offset));
7338 line2.move2side(MAX2(0.0, 0.5 * myType->getWidth() + offset));
7339 line2.scaleRelative(0.8);
7340 result.push_back(line1[0]);
7341 result.push_back(line2[0]);
7342 result.push_back(line2[1]);
7343 result.push_back(line1[1]);
7344 line1.move2side(MIN2(0.0, -0.6 * myType->getWidth() - offset));
7345 line2.move2side(MIN2(0.0, -1.0 * myType->getWidth() - offset));
7346 result.push_back(line1[1]);
7347 result.push_back(line2[1]);
7348 result.push_back(line2[0]);
7349 result.push_back(line1[0]);
7350 return result;
7351 }
7352 default:
7353 return getBoundingBox();
7354 }
7355}
7356
7357
7358bool
7360 for (std::vector<MSLane*>::const_iterator i = myFurtherLanes.begin(); i != myFurtherLanes.end(); ++i) {
7361 if (&(*i)->getEdge() == edge) {
7362 return true;
7363 }
7364 }
7365 return false;
7366}
7367
7368
7369bool
7370MSVehicle::isBidiOn(const MSLane* lane) const {
7371 return lane->getBidiLane() != nullptr && (
7372 myLane == lane->getBidiLane()
7373 || onFurtherEdge(&lane->getBidiLane()->getEdge()));
7374}
7375
7376
7377bool
7378MSVehicle::rerouteParkingArea(const std::string& parkingAreaID, std::string& errorMsg) {
7379 // this function is based on MSTriggeredRerouter::rerouteParkingArea in order to keep
7380 // consistency in the behaviour.
7381
7382 // get vehicle params
7383 MSParkingArea* destParkArea = getNextParkingArea();
7384 const MSRoute& route = getRoute();
7385 const MSEdge* lastEdge = route.getLastEdge();
7386
7387 if (destParkArea == nullptr) {
7388 // not driving towards a parking area
7389 errorMsg = "Vehicle " + getID() + " is not driving to a parking area so it cannot be rerouted.";
7390 return false;
7391 }
7392
7393 // if the current route ends at the parking area, the new route will also and at the new area
7394 bool newDestination = (&destParkArea->getLane().getEdge() == route.getLastEdge()
7395 && getArrivalPos() >= destParkArea->getBeginLanePosition()
7396 && getArrivalPos() <= destParkArea->getEndLanePosition());
7397
7398 // retrieve info on the new parking area
7400 parkingAreaID, SumoXMLTag::SUMO_TAG_PARKING_AREA);
7401
7402 if (newParkingArea == nullptr) {
7403 errorMsg = "Parking area ID " + toString(parkingAreaID) + " not found in the network.";
7404 return false;
7405 }
7406
7407 const MSEdge* newEdge = &(newParkingArea->getLane().getEdge());
7409
7410 // Compute the route from the current edge to the parking area edge
7411 ConstMSEdgeVector edgesToPark;
7412 router.compute(getEdge(), getPositionOnLane(), newEdge, newParkingArea->getEndLanePosition(), this, MSNet::getInstance()->getCurrentTimeStep(), edgesToPark);
7413
7414 // Compute the route from the parking area edge to the end of the route
7415 ConstMSEdgeVector edgesFromPark;
7416 if (!newDestination) {
7417 router.compute(newEdge, lastEdge, this, MSNet::getInstance()->getCurrentTimeStep(), edgesFromPark);
7418 } else {
7419 // adapt plans of any riders
7420 for (MSTransportable* p : getPersons()) {
7421 p->rerouteParkingArea(getNextParkingArea(), newParkingArea);
7422 }
7423 }
7424
7425 // we have a new destination, let's replace the vehicle route
7426 ConstMSEdgeVector edges = edgesToPark;
7427 if (edgesFromPark.size() > 0) {
7428 edges.insert(edges.end(), edgesFromPark.begin() + 1, edgesFromPark.end());
7429 }
7430
7432 SUMOVehicleParameter* newParameter = new SUMOVehicleParameter();
7433 *newParameter = getParameter();
7435 newParameter->arrivalPos = newParkingArea->getEndLanePosition();
7436 replaceParameter(newParameter);
7437 }
7438 const double routeCost = router.recomputeCosts(edges, this, MSNet::getInstance()->getCurrentTimeStep());
7439 ConstMSEdgeVector prevEdges(myCurrEdge, myRoute->end());
7440 const double savings = router.recomputeCosts(prevEdges, this, MSNet::getInstance()->getCurrentTimeStep());
7441 if (replaceParkingArea(newParkingArea, errorMsg)) {
7442 const bool onInit = myLane == nullptr;
7443 replaceRouteEdges(edges, routeCost, savings, "TraCI:" + toString(SUMO_TAG_PARKING_AREA_REROUTE), onInit, false, false);
7444 } else {
7445 WRITE_WARNINGF("Vehicle '%' could not reroute to new parkingArea '%' reason=%, time=%.",
7446 getID(), newParkingArea->getID(), errorMsg, time2string(SIMSTEP));
7447 return false;
7448 }
7449 return true;
7450}
7451
7452
7453bool
7455 const int numStops = (int)myStops.size();
7456 const bool result = MSBaseVehicle::addTraciStop(stop, errorMsg);
7457 if (myLane != nullptr && numStops != (int)myStops.size()) {
7458 updateBestLanes(true);
7459 }
7460 return result;
7461}
7462
7463
7464bool
7465MSVehicle::handleCollisionStop(MSStop& stop, const double distToStop) {
7466 if (myCurrEdge == stop.edge && distToStop + POSITION_EPS < getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0)) {
7467 if (distToStop < getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getEmergencyDecel(), 0)) {
7468 double vNew = getCarFollowModel().maximumSafeStopSpeed(distToStop, getCarFollowModel().getMaxDecel(), getSpeed(), false, 0);
7469 //std::cout << SIMTIME << " veh=" << getID() << " v=" << myState.mySpeed << " distToStop=" << distToStop
7470 // << " vMinNex=" << getCarFollowModel().minNextSpeed(getSpeed(), this)
7471 // << " bg1=" << getCarFollowModel().brakeGap(myState.mySpeed)
7472 // << " bg2=" << getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getEmergencyDecel(), 0)
7473 // << " vNew=" << vNew
7474 // << "\n";
7475 myState.mySpeed = MIN2(myState.mySpeed, vNew + ACCEL2SPEED(getCarFollowModel().getEmergencyDecel()));
7478 if (myState.myPos < myType->getLength()) {
7482 myAngle += M_PI;
7483 }
7484 }
7485 }
7486 }
7487 return true;
7488}
7489
7490
7491bool
7493 if (isStopped()) {
7497 }
7498 MSStop& stop = myStops.front();
7499 // we have waited long enough and fulfilled any passenger-requirements
7500 if (stop.busstop != nullptr) {
7501 // inform bus stop about leaving it
7502 stop.busstop->leaveFrom(this);
7503 }
7504 // we have waited long enough and fulfilled any container-requirements
7505 if (stop.containerstop != nullptr) {
7506 // inform container stop about leaving it
7507 stop.containerstop->leaveFrom(this);
7508 }
7509 if (stop.parkingarea != nullptr && stop.getSpeed() <= 0) {
7510 // inform parking area about leaving it
7511 stop.parkingarea->leaveFrom(this);
7512 }
7513 if (stop.chargingStation != nullptr) {
7514 // inform charging station about leaving it
7515 stop.chargingStation->leaveFrom(this);
7516 }
7517 // the current stop is no longer valid
7518 myLane->getEdge().removeWaiting(this);
7519 // MSStopOut needs to know whether the stop had a loaded 'ended' value so we call this before replacing the value
7520 if (stop.pars.started == -1) {
7521 // waypoint edge was passed in a single step
7523 }
7524 if (MSStopOut::active()) {
7525 MSStopOut::getInstance()->stopEnded(this, stop);
7526 }
7528 for (const auto& rem : myMoveReminders) {
7529 rem.first->notifyStopEnded();
7530 }
7532 myCollisionImmunity = TIME2STEPS(5); // leave the conflict area
7533 }
7535 // reset lateral position to default
7536 myState.myPosLat = 0;
7537 }
7538 const bool wasWaypoint = stop.getSpeed() > 0;
7539 myPastStops.push_back(stop.pars);
7540 myPastStops.back().routeIndex = (int)(stop.edge - myRoute->begin());
7541 myStops.pop_front();
7542 myStopDist = std::numeric_limits<double>::max();
7543 // do not count the stopping time towards gridlock time.
7544 // Other outputs use an independent counter and are not affected.
7545 myWaitingTime = 0;
7547 // maybe the next stop is on the same edge; let's rebuild best lanes
7548 updateBestLanes(true);
7549 // continue as wished...
7552 return !wasWaypoint;
7553 }
7554 return false;
7555}
7556
7557
7560 if (myInfluencer == nullptr) {
7561 myInfluencer = new Influencer();
7562 }
7563 return *myInfluencer;
7564}
7565
7570
7571
7574 return myInfluencer;
7575}
7576
7579 return myInfluencer;
7580}
7581
7582
7583double
7585 if (myInfluencer != nullptr && myInfluencer->getOriginalSpeed() >= 0) {
7586 // influencer original speed is -1 on initialization
7588 }
7589 return myState.mySpeed;
7590}
7591
7592
7593int
7595 if (hasInfluencer()) {
7597 MSNet::getInstance()->getCurrentTimeStep(),
7598 myLane->getEdge(),
7599 getLaneIndex(),
7600 state);
7601 }
7602 return state;
7603}
7604
7605
7606void
7610
7611
7612bool
7616
7617
7618bool
7622
7623
7624bool
7625MSVehicle::keepClear(const MSLink* link) const {
7626 if (link->hasFoes() && link->keepClear() /* && item.myLink->willHaveBlockedFoe()*/) {
7627 const double keepClearTime = getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_KEEPCLEAR_TIME, -1);
7628 //std::cout << SIMTIME << " veh=" << getID() << " keepClearTime=" << keepClearTime << " accWait=" << getAccumulatedWaitingSeconds() << " keepClear=" << (keepClearTime < 0 || getAccumulatedWaitingSeconds() < keepClearTime) << "\n";
7629 return keepClearTime < 0 || getAccumulatedWaitingSeconds() < keepClearTime;
7630 } else {
7631 return false;
7632 }
7633}
7634
7635
7636bool
7637MSVehicle::ignoreRed(const MSLink* link, bool canBrake) const {
7638 if ((myInfluencer != nullptr && !myInfluencer->getEmergencyBrakeRedLight())) {
7639 return true;
7640 }
7641 const double ignoreRedTime = getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_DRIVE_AFTER_RED_TIME, -1);
7642#ifdef DEBUG_IGNORE_RED
7643 if (DEBUG_COND) {
7644 std::cout << SIMTIME << " veh=" << getID() << " link=" << link->getViaLaneOrLane()->getID() << " state=" << toString(link->getState()) << "\n";
7645 }
7646#endif
7647 if (ignoreRedTime < 0) {
7648 const double ignoreYellowTime = getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_DRIVE_AFTER_YELLOW_TIME, 0);
7649 if (ignoreYellowTime > 0 && link->haveYellow()) {
7650 assert(link->getTLLogic() != 0);
7651 const double yellowDuration = STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep() - link->getLastStateChange());
7652 // when activating ignoreYellow behavior, vehicles will drive if they cannot brake
7653 return !canBrake || ignoreYellowTime > yellowDuration;
7654 } else {
7655 return false;
7656 }
7657 } else if (link->haveYellow()) {
7658 // always drive at yellow when ignoring red
7659 return true;
7660 } else if (link->haveRed()) {
7661 assert(link->getTLLogic() != 0);
7662 const double redDuration = STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep() - link->getLastStateChange());
7663#ifdef DEBUG_IGNORE_RED
7664 if (DEBUG_COND) {
7665 std::cout
7666 // << SIMTIME << " veh=" << getID() << " link=" << link->getViaLaneOrLane()->getID()
7667 << " ignoreRedTime=" << ignoreRedTime
7668 << " spentRed=" << redDuration
7669 << " canBrake=" << canBrake << "\n";
7670 }
7671#endif
7672 // when activating ignoreRed behavior, vehicles will always drive if they cannot brake
7673 return !canBrake || ignoreRedTime > redDuration;
7674 } else {
7675 return false;
7676 }
7677}
7678
7679bool
7682 return false;
7683 }
7684 for (const std::string& typeID : StringTokenizer(getParameter().getParameter(toString(SUMO_ATTR_CF_IGNORE_TYPES), "")).getVector()) {
7685 if (typeID == foe->getVehicleType().getID()) {
7686 return true;
7687 }
7688 }
7689 for (const std::string& id : StringTokenizer(getParameter().getParameter(toString(SUMO_ATTR_CF_IGNORE_IDS), "")).getVector()) {
7690 if (id == foe->getID()) {
7691 return true;
7692 }
7693 }
7694 return false;
7695}
7696
7697bool
7699 // either on an internal lane that was entered via minor link
7700 // or on approach to minor link below visibility distance
7701 if (myLane == nullptr) {
7702 return false;
7703 }
7704 if (myLane->getEdge().isInternal()) {
7705 return !myLane->getIncomingLanes().front().viaLink->havePriority();
7706 } else if (myLFLinkLanes.size() > 0 && myLFLinkLanes.front().myLink != nullptr) {
7707 MSLink* link = myLFLinkLanes.front().myLink;
7708 return !link->havePriority() && myLFLinkLanes.front().myDistance <= link->getFoeVisibilityDistance();
7709 }
7710 return false;
7711}
7712
7713bool
7714MSVehicle::isLeader(const MSLink* link, const MSVehicle* veh, const double gap) const {
7715 assert(link->fromInternalLane());
7716 if (veh == nullptr) {
7717 return false;
7718 }
7719 if (!myLane->isInternal() || myLane->getEdge().getToJunction() != link->getJunction()) {
7720 // if this vehicle is not yet on the junction, every vehicle is a leader
7721 return true;
7722 }
7723 if (veh->getLaneChangeModel().hasBlueLight()) {
7724 // blue light device automatically gets right of way
7725 return true;
7726 }
7727 const MSLane* foeLane = veh->getLane();
7728 if (foeLane->isInternal()) {
7729 if (foeLane->getEdge().getFromJunction() == link->getJunction()) {
7731 SUMOTime foeET = veh->myJunctionEntryTime;
7732 // check relationship between link and foeLane
7734 // we are entering the junction from the same lane
7736 foeET = veh->myJunctionEntryTimeNeverYield;
7739 }
7740 } else {
7741 const MSLink* foeLink = foeLane->getIncomingLanes()[0].viaLink;
7742 const MSJunctionLogic* logic = link->getJunction()->getLogic();
7743 assert(logic != nullptr);
7744 // determine who has right of way
7745 bool response; // ego response to foe
7746 bool response2; // foe response to ego
7747 // attempt 1: tlLinkState
7748 const MSLink* entry = link->getCorrespondingEntryLink();
7749 const MSLink* foeEntry = foeLink->getCorrespondingEntryLink();
7750 if (entry->haveRed() || foeEntry->haveRed()) {
7751 // ensure that vehicles which are stuck on the intersection may exit
7752 if (!foeEntry->haveRed() && veh->getSpeed() > SUMO_const_haltingSpeed && gap < 0) {
7753 // foe might be oncoming, don't drive unless foe can still brake safely
7754 const double foeNextSpeed = veh->getSpeed() + ACCEL2SPEED(veh->getCarFollowModel().getMaxAccel());
7755 const double foeBrakeGap = veh->getCarFollowModel().brakeGap(
7756 foeNextSpeed, veh->getCarFollowModel().getMaxDecel(), veh->getCarFollowModel().getHeadwayTime());
7757 // the minGap was subtracted from gap in MSLink::getLeaderInfo (enlarging the negative gap)
7758 // so the -2* makes it point in the right direction
7759 const double foeGap = -gap - veh->getLength() - 2 * getVehicleType().getMinGap();
7760#ifdef DEBUG_PLAN_MOVE_LEADERINFO
7761 if (DEBUG_COND) {
7762 std::cout << " foeGap=" << foeGap << " foeBGap=" << foeBrakeGap << "\n";
7763
7764 }
7765#endif
7766 if (foeGap < foeBrakeGap) {
7767 response = true;
7768 response2 = false;
7769 } else {
7770 response = false;
7771 response2 = true;
7772 }
7773 } else {
7774 // let conflict entry time decide
7775 response = true;
7776 response2 = true;
7777 }
7778 } else if (entry->havePriority() != foeEntry->havePriority()) {
7779 response = !entry->havePriority();
7780 response2 = !foeEntry->havePriority();
7781 } else if (entry->haveYellow() && foeEntry->haveYellow()) {
7782 // let the faster vehicle keep moving
7783 response = veh->getSpeed() >= getSpeed();
7784 response2 = getSpeed() >= veh->getSpeed();
7785 } else {
7786 // fallback if pedestrian crossings are involved
7787 response = logic->getResponseFor(link->getIndex()).test(foeLink->getIndex());
7788 response2 = logic->getResponseFor(foeLink->getIndex()).test(link->getIndex());
7789 }
7790#ifdef DEBUG_PLAN_MOVE_LEADERINFO
7791 if (DEBUG_COND) {
7792 std::cout << SIMTIME
7793 << " foeLane=" << foeLane->getID()
7794 << " foeLink=" << foeLink->getViaLaneOrLane()->getID()
7795 << " linkIndex=" << link->getIndex()
7796 << " foeLinkIndex=" << foeLink->getIndex()
7797 << " entryState=" << toString(entry->getState())
7798 << " entryState2=" << toString(foeEntry->getState())
7799 << " response=" << response
7800 << " response2=" << response2
7801 << "\n";
7802 }
7803#endif
7804 if (!response) {
7805 // if we have right of way over the foe, entryTime does not matter
7806 foeET = veh->myJunctionConflictEntryTime;
7807 egoET = myJunctionEntryTime;
7808 } else if (response && response2) {
7809 // in a mutual conflict scenario, use entry time to avoid deadlock
7810 foeET = veh->myJunctionConflictEntryTime;
7812 }
7813 }
7814 if (egoET == foeET) {
7815 // try to use speed as tie braker
7816 if (getSpeed() == veh->getSpeed()) {
7817 // use ID as tie braker
7818#ifdef DEBUG_PLAN_MOVE_LEADERINFO
7819 if (DEBUG_COND) {
7820 std::cout << SIMTIME << " veh=" << getID() << " equal ET " << egoET << " with foe " << veh->getID()
7821 << " foeIsLeaderByID=" << (getID() < veh->getID()) << "\n";
7822 }
7823#endif
7824 return getID() < veh->getID();
7825 } else {
7826#ifdef DEBUG_PLAN_MOVE_LEADERINFO
7827 if (DEBUG_COND) {
7828 std::cout << SIMTIME << " veh=" << getID() << " equal ET " << egoET << " with foe " << veh->getID()
7829 << " foeIsLeaderBySpeed=" << (getSpeed() < veh->getSpeed())
7830 << " v=" << getSpeed() << " foeV=" << veh->getSpeed()
7831 << "\n";
7832 }
7833#endif
7834 return getSpeed() < veh->getSpeed();
7835 }
7836 } else {
7837 // leader was on the junction first
7838#ifdef DEBUG_PLAN_MOVE_LEADERINFO
7839 if (DEBUG_COND) {
7840 std::cout << SIMTIME << " veh=" << getID() << " egoET " << egoET << " with foe " << veh->getID()
7841 << " foeET=" << foeET << " isLeader=" << (egoET > foeET) << "\n";
7842 }
7843#endif
7844 return egoET > foeET;
7845 }
7846 } else {
7847 // vehicle can only be partially on the junction. Must be a leader
7848 return true;
7849 }
7850 } else {
7851 // vehicle can only be partially on the junction. Must be a leader
7852 return true;
7853 }
7854}
7855
7856void
7859 // here starts the vehicle internal part (see loading)
7860 std::vector<std::string> internals;
7861 internals.push_back(toString(myParameter->parametersSet));
7862 internals.push_back(toString(myDeparture));
7863 internals.push_back(toString(distance(myRoute->begin(), myCurrEdge)));
7864 internals.push_back(toString(myDepartPos));
7865 internals.push_back(toString(myWaitingTime));
7866 internals.push_back(toString(myTimeLoss));
7867 internals.push_back(toString(myLastActionTime));
7868 internals.push_back(toString(isStopped()));
7869 internals.push_back(toString(isStopped() ? myStops.front().duration : 0));
7870 internals.push_back(toString(myPastStops.size()));
7871 internals.push_back(toString(myJunctionEntryTime));
7872 internals.push_back(toString(myJunctionConflictEntryTime));
7873 internals.push_back(toString(myJunctionEntryTimeNeverYield));
7874 out.writeAttr(SUMO_ATTR_STATE, internals);
7876 out.writeAttr(SUMO_ATTR_SPEED, std::vector<double> { myState.mySpeed, myState.myPreviousSpeed });
7880 if (isStopped() && myStops.front().entryPos != getPositionOnLane()) {
7881 out.writeAttr(SUMO_ATTR_ENTRYPOS, myStops.front().entryPos);
7882 }
7884 // save past stops
7886 stop.write(out, false);
7887 // do not write started and ended twice
7888 if ((stop.parametersSet & STOP_STARTED_SET) == 0) {
7889 out.writeAttr(SUMO_ATTR_STARTED, time2string(stop.started));
7890 }
7891 if ((stop.parametersSet & STOP_ENDED_SET) == 0) {
7892 out.writeAttr(SUMO_ATTR_ENDED, time2string(stop.ended));
7893 }
7894 XMLHelpers::writeParams(out, stop);
7895 out.closeTag();
7896 }
7897 // save upcoming stops
7898 for (MSStop& stop : myStops) {
7899 stop.write(out);
7900 }
7901 // save parameters and device states
7903 for (MSVehicleDevice* const dev : myDevices) {
7904 dev->saveState(out);
7905 }
7906 if (myCFVariables != nullptr) {
7908 }
7909 out.closeTag();
7910}
7911
7912void
7914 if (!attrs.hasAttribute(SUMO_ATTR_POSITION)) {
7915 throw ProcessError(TL("Error: Invalid vehicles in state (may be a meso state)!"));
7916 }
7917 bool ok;
7918 int routeOffset;
7919 bool stopped;
7920 SUMOTime stopDuration;
7921 int pastStops;
7922
7923 std::istringstream bis(attrs.getString(SUMO_ATTR_STATE));
7924 bis >> myParameter->parametersSet;
7925 bis >> myDeparture;
7926 bis >> routeOffset;
7927 bis >> myDepartPos;
7928 bis >> myWaitingTime;
7929 bis >> myTimeLoss;
7930 bis >> myLastActionTime;
7931 bis >> stopped;
7932 bis >> stopDuration;
7933 bis >> pastStops;
7934 bis >> myJunctionEntryTime;
7937
7939 myArrivalPos = attrs.get<double>(SUMO_ATTR_ARRIVALPOS_RANDOMIZED, getID().c_str(), ok);
7940 }
7941 // load stops
7942 myStops.clear();
7944
7945 if (hasDeparted()) {
7946 myCurrEdge = myRoute->begin() + routeOffset;
7947 myDeparture -= offset;
7948 // fix stops
7949 while (pastStops > 0) {
7950 SUMOVehicleParameter::Stop& pars = const_cast<SUMOVehicleParameter::Stop&>(myStops.front().pars);
7951 // assumed these attributes were only added to restore vehroute-output.exit-times
7953 pars.parametersSet &= ~STOP_ENDED_SET;
7954 }
7956 pars.parametersSet &= ~STOP_STARTED_SET;
7957 }
7958 for (const auto& rem : myMoveReminders) {
7959 rem.first->notifyStopEnded();
7960 }
7961 myPastStops.push_back(myStops.front().pars);
7962 myPastStops.back().routeIndex = (int)(myStops.front().edge - myRoute->begin());
7963 myStops.pop_front();
7964 pastStops--;
7965 }
7966 // see MSBaseVehicle constructor
7969 }
7970 // a (tentative lane is needed for calling hasArrivedInternal
7971 myLane = (*myCurrEdge)->getLanes()[0];
7972 }
7975 WRITE_WARNINGF(TL("Action steps are out of sync for loaded vehicle '%'."), getID());
7976 }
7977 std::istringstream pis(attrs.getString(SUMO_ATTR_POSITION));
7979 std::istringstream sis(attrs.getString(SUMO_ATTR_SPEED));
7985 std::istringstream dis(attrs.getString(SUMO_ATTR_DISTANCE));
7986 dis >> myOdometer >> myNumberReroutes;
7988 if (stopped) {
7989 double realPos = getPositionOnLane();
7990 double entryPos = attrs.getOpt<double>(SUMO_ATTR_ENTRYPOS, getID().c_str(), ok, realPos);
7991 myStops.front().startedFromState = true;
7992 if (entryPos != realPos) {
7993 myStops.front().entryPos = entryPos;
7994 }
7995 myLane = const_cast<MSLane*>(myStops.front().lane);
7996 myStopDist = 0;
7997 myState.myPos = entryPos; // fake position for replication stop entry which happened before the position was updated
7999 myState.myPos = realPos; // reset fake position
8000 if (myStops.front().pars.parking != ParkingType::ONROAD) {
8001 // processNextStop is called again during MSVehicleTransfer::loadState
8002 stopDuration += getActionStepLength();
8003 }
8004 myStops.front().duration = stopDuration;
8006 SUMOVehicleParameter::Stop& pars = const_cast<SUMOVehicleParameter::Stop&>(myStops.front().pars);
8007 pars.parametersSet &= ~STOP_STARTED_SET;
8008 }
8009 }
8011 // no need to reset myCachedPosition here since state loading happens directly after creation
8012}
8013
8014void
8016 SUMOTime arrivalTime, double arrivalSpeed,
8017 double arrivalSpeedBraking,
8018 double dist, double leaveSpeed) {
8019 // ensure that approach information is reset on the next call to setApproachingForAllLinks
8020 myLFLinkLanes.push_back(DriveProcessItem(link, 0, 0, setRequest,
8021 arrivalTime, arrivalSpeed, arrivalSpeedBraking, dist, leaveSpeed));
8022
8023}
8024
8025
8026std::shared_ptr<MSSimpleDriverState>
8030
8031
8032double
8034 return myFrictionDevice == nullptr ? 1. : myFrictionDevice->getMeasuredFriction();
8035}
8036
8037
8038void
8039MSVehicle::setPreviousSpeed(double prevSpeed, double prevAcceleration) {
8040 myState.mySpeed = MAX2(0., prevSpeed);
8041 // also retcon acceleration
8042 if (prevAcceleration != std::numeric_limits<double>::min()) {
8043 myAcceleration = prevAcceleration;
8044 } else {
8046 }
8047}
8048
8049
8050double
8052 //return MAX2(-myAcceleration, getCarFollowModel().getApparentDecel());
8054}
8055
8056/****************************************************************************/
8057bool
8061
8062/* -------------------------------------------------------------------------
8063 * methods of MSVehicle::manoeuvre
8064 * ----------------------------------------------------------------------- */
8065
8066MSVehicle::Manoeuvre::Manoeuvre() : myManoeuvreStop(""), myManoeuvreStartTime(0), myManoeuvreCompleteTime(0), myManoeuvreType(MSVehicle::MANOEUVRE_NONE), myGUIIncrement(0) {}
8067
8068
8070 myManoeuvreStop = manoeuvre.myManoeuvreStop;
8071 myManoeuvreStartTime = manoeuvre.myManoeuvreStartTime;
8072 myManoeuvreCompleteTime = manoeuvre.myManoeuvreCompleteTime;
8073 myManoeuvreType = manoeuvre.myManoeuvreType;
8074 myGUIIncrement = manoeuvre.myGUIIncrement;
8075}
8076
8077
8080 myManoeuvreStop = manoeuvre.myManoeuvreStop;
8081 myManoeuvreStartTime = manoeuvre.myManoeuvreStartTime;
8082 myManoeuvreCompleteTime = manoeuvre.myManoeuvreCompleteTime;
8083 myManoeuvreType = manoeuvre.myManoeuvreType;
8084 myGUIIncrement = manoeuvre.myGUIIncrement;
8085 return *this;
8086}
8087
8088
8089bool
8091 return (myManoeuvreStop != manoeuvre.myManoeuvreStop ||
8092 myManoeuvreStartTime != manoeuvre.myManoeuvreStartTime ||
8093 myManoeuvreCompleteTime != manoeuvre.myManoeuvreCompleteTime ||
8094 myManoeuvreType != manoeuvre.myManoeuvreType ||
8095 myGUIIncrement != manoeuvre.myGUIIncrement
8096 );
8097}
8098
8099
8100double
8102 return (myGUIIncrement);
8103}
8104
8105
8108 return (myManoeuvreType);
8109}
8110
8111
8116
8117
8118void
8122
8123
8124void
8126 myManoeuvreType = mType;
8127}
8128
8129
8130bool
8132 if (!veh->hasStops()) {
8133 return false; // should never happen - checked before call
8134 }
8135
8136 const SUMOTime currentTime = MSNet::getInstance()->getCurrentTimeStep();
8137 const MSStop& stop = veh->getNextStop();
8138
8139 int manoeuverAngle = stop.parkingarea->getLastFreeLotAngle();
8140 double GUIAngle = stop.parkingarea->getLastFreeLotGUIAngle();
8141 if (abs(GUIAngle) < 0.1) {
8142 GUIAngle = -0.1; // Wiggle vehicle on parallel entry
8143 }
8144 myManoeuvreVehicleID = veh->getID();
8145 myManoeuvreStop = stop.parkingarea->getID();
8146 myManoeuvreType = MSVehicle::MANOEUVRE_ENTRY;
8147 myManoeuvreStartTime = currentTime;
8148 myManoeuvreCompleteTime = currentTime + veh->myType->getEntryManoeuvreTime(manoeuverAngle);
8149 myGUIIncrement = GUIAngle / (STEPS2TIME(myManoeuvreCompleteTime - myManoeuvreStartTime) / TS);
8150
8151#ifdef DEBUG_STOPS
8152 if (veh->isSelected()) {
8153 std::cout << "ENTRY manoeuvre start: vehicle=" << veh->getID() << " Manoeuvre Angle=" << manoeuverAngle << " Rotation angle=" << RAD2DEG(GUIAngle) << " Road Angle" << RAD2DEG(veh->getAngle()) << " increment=" << RAD2DEG(myGUIIncrement) << " currentTime=" << currentTime <<
8154 " endTime=" << myManoeuvreCompleteTime << " manoeuvre time=" << myManoeuvreCompleteTime - currentTime << " parkArea=" << myManoeuvreStop << std::endl;
8155 }
8156#endif
8157
8158 return (true);
8159}
8160
8161
8162bool
8164 // At the moment we only want to set for parking areas
8165 if (!veh->hasStops()) {
8166 return true;
8167 }
8168 if (veh->getNextStop().parkingarea == nullptr) {
8169 return true;
8170 }
8171
8172 if (myManoeuvreType != MSVehicle::MANOEUVRE_NONE) {
8173 return (false);
8174 }
8175
8176 const SUMOTime currentTime = MSNet::getInstance()->getCurrentTimeStep();
8177
8178 int manoeuverAngle = veh->getCurrentParkingArea()->getManoeuverAngle(*veh);
8179 double GUIAngle = veh->getCurrentParkingArea()->getGUIAngle(*veh);
8180 if (abs(GUIAngle) < 0.1) {
8181 GUIAngle = 0.1; // Wiggle vehicle on parallel exit
8182 }
8183
8184 myManoeuvreVehicleID = veh->getID();
8185 myManoeuvreStop = veh->getCurrentParkingArea()->getID();
8186 myManoeuvreType = MSVehicle::MANOEUVRE_EXIT;
8187 myManoeuvreStartTime = currentTime;
8188 myManoeuvreCompleteTime = currentTime + veh->myType->getExitManoeuvreTime(manoeuverAngle);
8189 myGUIIncrement = -GUIAngle / (STEPS2TIME(myManoeuvreCompleteTime - myManoeuvreStartTime) / TS);
8190 if (veh->remainingStopDuration() > 0) {
8191 myManoeuvreCompleteTime += veh->remainingStopDuration();
8192 }
8193
8194#ifdef DEBUG_STOPS
8195 if (veh->isSelected()) {
8196 std::cout << "EXIT manoeuvre start: vehicle=" << veh->getID() << " Manoeuvre Angle=" << manoeuverAngle << " increment=" << RAD2DEG(myGUIIncrement) << " currentTime=" << currentTime
8197 << " endTime=" << myManoeuvreCompleteTime << " manoeuvre time=" << myManoeuvreCompleteTime - currentTime << " parkArea=" << myManoeuvreStop << std::endl;
8198 }
8199#endif
8200
8201 return (true);
8202}
8203
8204
8205bool
8207 // At the moment we only want to consider parking areas - need to check because we could be setting up a manoeuvre
8208 if (!veh->hasStops()) {
8209 return (true);
8210 }
8211 MSStop* currentStop = &veh->myStops.front();
8212 if (currentStop->parkingarea == nullptr) {
8213 return true;
8214 } else if (currentStop->parkingarea->getID() != myManoeuvreStop || MSVehicle::MANOEUVRE_ENTRY != myManoeuvreType) {
8215 if (configureEntryManoeuvre(veh)) {
8217 return (false);
8218 } else { // cannot configure entry so stop trying
8219 return true;
8220 }
8221 } else if (MSNet::getInstance()->getCurrentTimeStep() < myManoeuvreCompleteTime) {
8222 return false;
8223 } else { // manoeuvre complete
8224 myManoeuvreType = MSVehicle::MANOEUVRE_NONE;
8225 return true;
8226 }
8227}
8228
8229
8230bool
8232 if (checkType != myManoeuvreType) {
8233 return true; // we're not maneuvering / wrong manoeuvre
8234 }
8235
8236 if (MSNet::getInstance()->getCurrentTimeStep() < myManoeuvreCompleteTime) {
8237 return false;
8238 } else {
8239 return true;
8240 }
8241}
8242
8243
8244bool
8246 return (MSNet::getInstance()->getCurrentTimeStep() >= myManoeuvreCompleteTime);
8247}
8248
8249
8250bool
8254
8255
8256std::pair<double, double>
8258 if (hasStops()) {
8259 MSLane* lane = myLane;
8260 if (lane == nullptr) {
8261 // not in network
8262 lane = getEdge()->getLanes()[0];
8263 }
8264 const MSStop& stop = myStops.front();
8265 auto it = myCurrEdge + 1;
8266 // drive to end of current edge
8267 double dist = (lane->getLength() - getPositionOnLane());
8268 double travelTime = lane->getEdge().getMinimumTravelTime(this) * dist / lane->getLength();
8269 // drive until stop edge
8270 while (it != myRoute->end() && it < stop.edge) {
8271 travelTime += (*it)->getMinimumTravelTime(this);
8272 dist += (*it)->getLength();
8273 it++;
8274 }
8275 // drive up to the stop position
8276 const double stopEdgeDist = stop.pars.endPos - (lane == stop.lane ? lane->getLength() : 0);
8277 dist += stopEdgeDist;
8278 travelTime += stop.lane->getEdge().getMinimumTravelTime(this) * (stopEdgeDist / stop.lane->getLength());
8279 // estimate time loss due to acceleration and deceleration
8280 // maximum speed is limited by available distance:
8281 const double a = getCarFollowModel().getMaxAccel();
8282 const double b = getCarFollowModel().getMaxDecel();
8283 const double c = getSpeed();
8284 const double d = dist;
8285 const double len = getVehicleType().getLength();
8286 const double vs = MIN2(MAX2(stop.getSpeed(), 0.0), stop.lane->getVehicleMaxSpeed(this));
8287 // distAccel = (v - c)^2 / (2a)
8288 // distDecel = (v + vs)*(v - vs) / 2b = (v^2 - vs^2) / (2b)
8289 // distAccel + distDecel < d
8290 const double maxVD = MAX2(c, ((sqrt(MAX2(0.0, pow(2 * c * b, 2) + (4 * ((b * ((a * (2 * d * (b + a) + (vs * vs) - (c * c))) - (b * (c * c))))
8291 + pow((a * vs), 2))))) * 0.5) + (c * b)) / (b + a));
8292 it = myCurrEdge;
8293 double v0 = c;
8294 bool v0Stable = getAcceleration() == 0 && v0 > 0;
8295 double timeLossAccel = 0;
8296 double timeLossDecel = 0;
8297 double timeLossLength = 0;
8298 while (it != myRoute->end() && it <= stop.edge) {
8299 double v = MIN2(maxVD, (*it)->getVehicleMaxSpeed(this));
8300 double edgeLength = (it == stop.edge ? stop.pars.endPos : (*it)->getLength()) - (it == myCurrEdge ? getPositionOnLane() : 0);
8301 if (edgeLength <= len && v0Stable && v0 < v) {
8302 const double lengthDist = MIN2(len, edgeLength);
8303 const double dTL = lengthDist / v0 - lengthDist / v;
8304 //std::cout << " e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " el=" << edgeLength << " lDist=" << lengthDist << " newTLL=" << dTL<< "\n";
8305 timeLossLength += dTL;
8306 }
8307 if (edgeLength > len) {
8308 const double dv = v - v0;
8309 if (dv > 0) {
8310 // timeLossAccel = timeAccel - timeMaxspeed = dv / a - distAccel / v
8311 const double dTA = dv / a - dv * (v + v0) / (2 * a * v);
8312 //std::cout << " e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLA=" << dTA << "\n";
8313 timeLossAccel += dTA;
8314 // time loss from vehicle length
8315 } else if (dv < 0) {
8316 // timeLossDecel = timeDecel - timeMaxspeed = dv / b - distDecel / v
8317 const double dTD = -dv / b + dv * (v + v0) / (2 * b * v0);
8318 //std::cout << " e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLD=" << dTD << "\n";
8319 timeLossDecel += dTD;
8320 }
8321 v0 = v;
8322 v0Stable = true;
8323 }
8324 it++;
8325 }
8326 // final deceleration to stop (may also be acceleration or deceleration to waypoint speed)
8327 double v = vs;
8328 const double dv = v - v0;
8329 if (dv > 0) {
8330 // timeLossAccel = timeAccel - timeMaxspeed = dv / a - distAccel / v
8331 const double dTA = dv / a - dv * (v + v0) / (2 * a * v);
8332 //std::cout << " final e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLA=" << dTA << "\n";
8333 timeLossAccel += dTA;
8334 // time loss from vehicle length
8335 } else if (dv < 0) {
8336 // timeLossDecel = timeDecel - timeMaxspeed = dv / b - distDecel / v
8337 const double dTD = -dv / b + dv * (v + v0) / (2 * b * v0);
8338 //std::cout << " final e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLD=" << dTD << "\n";
8339 timeLossDecel += dTD;
8340 }
8341 const double result = travelTime + timeLossAccel + timeLossDecel + timeLossLength;
8342 //std::cout << SIMTIME << " v=" << c << " a=" << a << " b=" << b << " maxVD=" << maxVD << " tt=" << travelTime
8343 // << " ta=" << timeLossAccel << " td=" << timeLossDecel << " tl=" << timeLossLength << " res=" << result << "\n";
8344 return {MAX2(0.0, result), dist};
8345 } else {
8347 }
8348}
8349
8350
8351double
8353 if (hasStops() && myStops.front().pars.until >= 0) {
8354 const MSStop& stop = myStops.front();
8355 SUMOTime estimatedDepart = MSNet::getInstance()->getCurrentTimeStep() - DELTA_T;
8356 if (stop.reached) {
8357 return STEPS2TIME(estimatedDepart + stop.duration - stop.pars.until);
8358 }
8359 if (stop.pars.duration > 0) {
8360 estimatedDepart += stop.pars.duration;
8361 }
8362 estimatedDepart += TIME2STEPS(estimateTimeToNextStop().first);
8363 const double result = MAX2(0.0, STEPS2TIME(estimatedDepart - stop.pars.until));
8364 return result;
8365 } else {
8366 // vehicles cannot drive before 'until' so stop delay can never be
8367 // negative and we can use -1 to signal "undefined"
8368 return -1;
8369 }
8370}
8371
8372
8373double
8375 if (hasStops() && myStops.front().pars.arrival >= 0) {
8376 const MSStop& stop = myStops.front();
8377 if (stop.reached) {
8378 return STEPS2TIME(stop.pars.started - stop.pars.arrival);
8379 } else {
8380 return STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep()) + estimateTimeToNextStop().first - STEPS2TIME(stop.pars.arrival);
8381 }
8382 } else {
8383 // vehicles can arrive earlier than planned so arrival delay can be negative
8384 return INVALID_DOUBLE;
8385 }
8386}
8387
8388
8389const MSEdge*
8391 return myLane != nullptr ? &myLane->getEdge() : getEdge();
8392}
8393
8394
8395const MSEdge*
8397 if (myLane == nullptr || (myCurrEdge + 1) == myRoute->end()) {
8398 return nullptr;
8399 }
8400 if (myLane->isInternal()) {
8402 } else {
8403 const MSEdge* nextNormal = succEdge(1);
8404 const MSEdge* nextInternal = myLane->getEdge().getInternalFollowingEdge(nextNormal, getVClass());
8405 return nextInternal ? nextInternal : nextNormal;
8406 }
8407}
8408
8409
8410const MSLane*
8411MSVehicle::getPreviousLane(const MSLane* current, int& furtherIndex) const {
8412 if (furtherIndex < (int)myFurtherLanes.size()) {
8413 return myFurtherLanes[furtherIndex++];
8414 } else {
8415 // try to use route information
8416 int routeIndex = getRoutePosition();
8417 bool resultInternal;
8418 if (MSGlobals::gUsingInternalLanes && MSNet::getInstance()->hasInternalLinks()) {
8419 if (myLane->isInternal()) {
8420 if (furtherIndex % 2 == 0) {
8421 routeIndex -= (furtherIndex + 0) / 2;
8422 resultInternal = false;
8423 } else {
8424 routeIndex -= (furtherIndex + 1) / 2;
8425 resultInternal = false;
8426 }
8427 } else {
8428 if (furtherIndex % 2 != 0) {
8429 routeIndex -= (furtherIndex + 1) / 2;
8430 resultInternal = false;
8431 } else {
8432 routeIndex -= (furtherIndex + 2) / 2;
8433 resultInternal = true;
8434 }
8435 }
8436 } else {
8437 routeIndex -= furtherIndex;
8438 resultInternal = false;
8439 }
8440 furtherIndex++;
8441 if (routeIndex >= 0) {
8442 if (resultInternal) {
8443 const MSEdge* prevNormal = myRoute->getEdges()[routeIndex];
8444 for (MSLane* cand : prevNormal->getLanes()) {
8445 for (MSLink* link : cand->getLinkCont()) {
8446 if (link->getLane() == current) {
8447 if (link->getViaLane() != nullptr) {
8448 return link->getViaLane();
8449 } else {
8450 return const_cast<MSLane*>(link->getLaneBefore());
8451 }
8452 }
8453 }
8454 }
8455 } else {
8456 return myRoute->getEdges()[routeIndex]->getLanes()[0];
8457 }
8458 }
8459 }
8460 return current;
8461}
8462
8465 // this vehicle currently has the highest priority on the allway_stop
8466 return link == myHaveStoppedFor ? SUMOTime_MAX : getWaitingTime();
8467}
8468
8469
8470void
8472 bool diverged = false;
8473 const ConstMSEdgeVector& route = myRoute->getEdges();
8474 int ri = getRoutePosition();
8475 for (const DriveProcessItem& dpi : myLFLinkLanes) {
8476 if (dpi.myLink != nullptr) {
8477 if (!diverged) {
8478 const MSEdge* next = route[ri + 1];
8479 if (&dpi.myLink->getLane()->getEdge() != next) {
8480 diverged = true;
8481 } else {
8482 if (dpi.myLink->getViaLane() == nullptr) {
8483 ri++;
8484 }
8485 }
8486 }
8487 if (diverged) {
8488 dpi.myLink->removeApproaching(this);
8489 }
8490 }
8491 }
8492}
8493
8494
8495bool
8499
8500/****************************************************************************/
long long int SUMOTime
Definition GUI.h:36
#define RAD2DEG(x)
Definition GeomHelper.h:36
#define DEBUG_COND2(obj)
std::vector< const MSEdge * > ConstMSEdgeVector
Definition MSEdge.h:75
std::vector< MSEdge * > MSEdgeVector
Definition MSEdge.h:74
std::pair< const MSVehicle *, double > CLeaderDist
std::pair< const MSPerson *, double > PersonDist
Definition MSPModel.h:41
ConstMSEdgeVector::const_iterator MSRouteIterator
Definition MSRoute.h:57
#define NUMERICAL_EPS_SPEED
#define STOPPING_PLACE_OFFSET
#define JUNCTION_BLOCKAGE_TIME
#define DIST_TO_STOPLINE_EXPECT_PRIORITY
#define CRLL_LOOK_AHEAD
#define WRITE_WARNINGF(...)
Definition MsgHandler.h:299
#define WRITE_ERROR(msg)
Definition MsgHandler.h:307
#define TL(string)
Definition MsgHandler.h:316
std::shared_ptr< const MSRoute > ConstMSRoutePtr
Definition Route.h:32
SUMOTime DELTA_T
Definition SUMOTime.cpp:39
SUMOTime string2time(const std::string &r)
convert string to SUMOTime
Definition SUMOTime.cpp:47
std::string time2string(SUMOTime t, bool humanReadable)
convert SUMOTime to string (independently of global format setting)
Definition SUMOTime.cpp:107
#define STEPS2TIME(x)
Definition SUMOTime.h:58
#define SPEED2DIST(x)
Definition SUMOTime.h:48
#define SIMSTEP
Definition SUMOTime.h:69
#define ACCEL2SPEED(x)
Definition SUMOTime.h:54
constexpr SUMOTime TIME2STEPS(double x)
Definition SUMOTime.h:60
#define SUMOTime_MAX
Definition SUMOTime.h:34
#define TS
Definition SUMOTime.h:45
#define SIMTIME
Definition SUMOTime.h:70
#define DIST2SPEED(x)
Definition SUMOTime.h:50
#define SPEED2ACCEL(x)
Definition SUMOTime.h:56
bool isRailway(SVCPermissions permissions)
Returns whether an edge with the given permissions is a (exclusive) railway edge.
@ RAIL_CARGO
render as a cargo train
@ RAIL
render as a rail
@ PASSENGER_VAN
render as a van
@ PASSENGER
render as a passenger vehicle
@ RAIL_CAR
render as a (city) rail without locomotive
@ PASSENGER_HATCHBACK
render as a hatchback passenger vehicle ("Fliessheck")
@ BUS_FLEXIBLE
render as a flexible city bus
@ TRUCK_1TRAILER
render as a transport vehicle with one trailer
@ PASSENGER_SEDAN
render as a sedan passenger vehicle ("Stufenheck")
@ PASSENGER_WAGON
render as a wagon passenger vehicle ("Combi")
@ TRUCK_SEMITRAILER
render as a semi-trailer transport vehicle ("Sattelschlepper")
@ SVC_RAIL_CLASSES
classes which drive on tracks
@ SVC_EMERGENCY
public emergency vehicles
const long long int VEHPARS_FORCE_REROUTE
@ GIVEN
The lane is given.
@ DEFAULT
No information given; use default.
@ GIVEN
The speed is given.
@ SPLIT_FRONT
depart position for a split vehicle is in front of the continuing vehicle
const long long int VEHPARS_CFMODEL_PARAMS_SET
@ GIVEN
The arrival lane is given.
@ GIVEN
The speed is given.
const int STOP_ENDED_SET
@ GIVEN
The arrival position is given.
@ DEFAULT
No information given; use default.
const int STOP_STARTED_SET
@ SUMO_TAG_PARKING_AREA_REROUTE
entry for an alternative parking zone
@ SUMO_TAG_PARKING_AREA
A parking area.
@ SUMO_TAG_OVERHEAD_WIRE_SEGMENT
An overhead wire segment.
LinkDirection
The different directions a link between two lanes may take (or a stream between two edges)....
@ PARTLEFT
The link is a partial left direction.
@ RIGHT
The link is a (hard) right direction.
@ TURN
The link is a 180 degree turn.
@ LEFT
The link is a (hard) left direction.
@ STRAIGHT
The link is a straight direction.
@ TURN_LEFTHAND
The link is a 180 degree turn (left-hand network)
@ PARTRIGHT
The link is a partial right direction.
@ NODIR
The link has no direction (is a dead end link)
LinkState
The right-of-way state of a link between two lanes used when constructing a NBTrafficLightLogic,...
@ LINKSTATE_ALLWAY_STOP
This is an uncontrolled, all-way stop link.
@ LINKSTATE_EQUAL
This is an uncontrolled, right-before-left link.
@ LINKSTATE_ZIPPER
This is an uncontrolled, zipper-merge link.
@ LCA_KEEPRIGHT
The action is due to the default of keeping right "Rechtsfahrgebot".
@ LCA_BLOCKED
blocked in all directions
@ LCA_URGENT
The action is urgent (to be defined by lc-model)
@ LCA_STAY
Needs to stay on the current lane.
@ LCA_SUBLANE
used by the sublane model
@ LCA_WANTS_LANECHANGE_OR_STAY
lane can change or stay
@ LCA_COOPERATIVE
The action is done to help someone else.
@ LCA_OVERLAPPING
The vehicle is blocked being overlapping.
@ LCA_LEFT
Wants go to the left.
@ LCA_STRATEGIC
The action is needed to follow the route (navigational lc)
@ LCA_TRACI
The action is due to a TraCI request.
@ LCA_SPEEDGAIN
The action is due to the wish to be faster (tactical lc)
@ LCA_RIGHT
Wants go to the right.
@ SUMO_ATTR_JM_STOPLINE_GAP_MINOR
@ SUMO_ATTR_JM_STOPLINE_CROSSING_GAP
@ SUMO_ATTR_JM_IGNORE_KEEPCLEAR_TIME
@ SUMO_ATTR_SPEED
@ SUMO_ATTR_STARTED
@ SUMO_ATTR_MAXIMUMPOWER
Maximum Power.
@ SUMO_ATTR_WAITINGTIME
@ SUMO_ATTR_CF_IGNORE_IDS
@ SUMO_ATTR_JM_STOPLINE_GAP
@ SUMO_ATTR_POSITION_LAT
@ SUMO_ATTR_JM_DRIVE_AFTER_RED_TIME
@ SUMO_ATTR_JM_DRIVE_AFTER_YELLOW_TIME
@ SUMO_ATTR_ENDED
@ SUMO_ATTR_LCA_CONTRIGHT
@ SUMO_ATTR_ANGLE
@ SUMO_ATTR_DISTANCE
@ SUMO_ATTR_CF_IGNORE_TYPES
@ SUMO_ATTR_ARRIVALPOS_RANDOMIZED
@ SUMO_ATTR_ENTRYPOS
@ SUMO_ATTR_FLEX_ARRIVAL
@ SUMO_ATTR_JM_IGNORE_JUNCTION_FOE_PROB
@ SUMO_ATTR_POSITION
@ SUMO_ATTR_STATE
The state of a link.
@ SUMO_ATTR_JM_DRIVE_RED_SPEED
int gPrecision
the precision for floating point outputs
Definition StdDefs.cpp:27
bool gDebugFlag1
global utility flags for debugging
Definition StdDefs.cpp:44
const double INVALID_DOUBLE
invalid double
Definition StdDefs.h:68
const double SUMO_const_laneWidth
Definition StdDefs.h:52
T MIN3(T a, T b, T c)
Definition StdDefs.h:93
T MIN2(T a, T b)
Definition StdDefs.h:80
const double SUMO_const_haltingSpeed
the speed threshold at which vehicles are considered as halting
Definition StdDefs.h:62
T MAX2(T a, T b)
Definition StdDefs.h:86
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition ToString.h:57
#define SOFT_ASSERT(expr)
define SOFT_ASSERT raise an assertion in debug mode everywhere except on the windows test server
double getDoubleOptional(SumoXMLAttr attr, const double def) const
Returns the value for a given key with an optional default. SUMO_ATTR_MASS and SUMO_ATTR_FRONTSURFACE...
void setDynamicValues(const SUMOTime stopDuration, const bool parking, const SUMOTime waitingTime, const double angleDiff)
Sets the values which change possibly in every simulation step and are relevant for emsssion calculat...
static double naviDegree(const double angle)
static double fromNaviDegree(const double angle)
static double angleDiff(const double angle1, const double angle2)
Returns the difference of the second angle to the first angle in radiants.
Interface for lane-change models.
double getLaneChangeCompletion() const
Get the current lane change completion ratio.
const std::vector< double > & getShadowFurtherLanesPosLat() const
double getManeuverDist() const
Returns the remaining unblocked distance for the current maneuver. (only used by sublane model)
int getLaneChangeDirection() const
return the direction of the current lane change maneuver
void resetChanged()
reset the flag whether a vehicle already moved to false
MSLane * getShadowLane() const
Returns the lane the vehicle's shadow is on during continuous/sublane lane change.
virtual void saveState(OutputDevice &out) const
Save the state of the laneChangeModel.
void endLaneChangeManeuver(const MSMoveReminder::Notification reason=MSMoveReminder::NOTIFICATION_LANE_CHANGE)
void setNoShadowPartialOccupator(MSLane *lane)
MSLane * getTargetLane() const
Returns the lane the vehicle has committed to enter during a sublane lane change.
SUMOTime remainingTime() const
Compute the remaining time until LC completion.
void setShadowApproachingInformation(MSLink *link) const
set approach information for the shadow vehicle
double getCooperativeHelpSpeed(const MSLane *lane, double distToLaneEnd) const
return speed for helping a vehicle that is blocked from changing
static MSAbstractLaneChangeModel * build(LaneChangeModel lcm, MSVehicle &vehicle)
Factory method for instantiating new lane changing models.
void changedToOpposite()
called when a vehicle changes between lanes in opposite directions
int getShadowDirection() const
return the direction in which the current shadow lane lies
virtual void loadState(const SUMOSAXAttributes &attrs)
Loads the state of the laneChangeModel from the given attributes.
double calcAngleOffset()
return the angle offset during a continuous change maneuver
void setPreviousAngleOffset(const double angleOffset)
set the angle offset of the previous time step
const std::vector< MSLane * > & getFurtherTargetLanes() const
double getAngleOffset() const
return the angle offset resulting from lane change and sigma
virtual void prepareStep(SumoRNG *rng)
rng belongs to the lane that moves the vehicle (not the lane it just entered)
const std::vector< MSLane * > & getShadowFurtherLanes() const
bool isChangingLanes() const
return true if the vehicle currently performs a lane change maneuver
void setExtraImpatience(double value)
Sets routing behavior.
The base class for microscopic and mesoscopic vehicles.
double getMaxSpeed() const
Returns the maximum speed (the minimum of desired and technical maximum speed)
bool haveValidStopEdges(bool silent=false) const
check whether all stop.edge MSRouteIterators are valid and in order
virtual bool isSelected() const
whether this vehicle is selected in the GUI
std::list< MSStop > myStops
The vehicle's list of stops.
double getImpatience() const
Returns this vehicles impatience.
const std::vector< MSTransportable * > & getPersons() const
retrieve riding persons
virtual void initDevices()
const MSEdge * succEdge(int nSuccs) const
Returns the nSuccs'th successor of edge the vehicle is currently at.
void calculateArrivalParams(bool onInit)
(Re-)Calculates the arrival position and lane from the vehicle parameters
virtual double getArrivalPos() const
Returns this vehicle's desired arrivalPos for its current route (may change on reroute)
MoveReminderCont myMoveReminders
Currently relevant move reminders.
double myDepartPos
The real depart position.
const SUMOVehicleParameter & getParameter() const
Returns the vehicle's parameter (including departure definition)
void replaceParameter(const SUMOVehicleParameter *newParameter)
replace the vehicle parameter (deleting the old one)
double getChosenSpeedFactor() const
Returns the precomputed factor by which the driver wants to be faster than the speed limit.
std::vector< MSVehicleDevice * > myDevices
The devices this vehicle has.
virtual void addTransportable(MSTransportable *transportable)
Adds a person or container to this vehicle.
const SUMOVehicleParameter::Stop * getNextStopParameter() const
return parameters for the next stop (SUMOVehicle Interface)
virtual bool replaceRoute(ConstMSRoutePtr route, const std::string &info, bool onInit=false, int offset=0, bool addRouteStops=true, bool removeStops=true, std::string *msgReturn=nullptr)
Replaces the current route by the given one.
bool isRail() const
MSVehicleType & getSingularType()
Replaces the current vehicle type with a new one used by this vehicle only.
const MSVehicleType * myType
This vehicle's type.
void cleanupParkingReservation()
unregisters from a parking reservation when changing or skipping stops
double getLength() const
Returns the vehicle's length.
bool isParking() const
Returns whether the vehicle is parking.
MSParkingArea * getCurrentParkingArea()
get the current parking area stop or nullptr
const MSEdge * getEdge() const
Returns the edge the vehicle is currently at.
int getPersonNumber() const
Returns the number of persons.
MSRouteIterator myCurrEdge
Iterator to current route-edge.
StopParVector myPastStops
The list of stops that the vehicle has already reached.
bool hasDeparted() const
Returns whether this vehicle has already departed.
bool ignoreTransientPermissions() const
Returns whether this object is ignoring transient permission changes (during routing)
ConstMSRoutePtr myRoute
This vehicle's route.
double getWidth() const
Returns the vehicle's width.
MSDevice_Transportable * myContainerDevice
The containers this vehicle may have.
const std::list< MSStop > & getStops() const
double getDesiredMaxSpeed() const
void addReminder(MSMoveReminder *rem, double pos=0)
Adds a MoveReminder dynamically.
SumoRNG * getRNG() const
SUMOTime getDeparture() const
Returns this vehicle's real departure time.
EnergyParams * getEmissionParameters() const
retrieve parameters for the energy consumption model
MSDevice_Transportable * myPersonDevice
The passengers this vehicle may have.
bool hasStops() const
Returns whether the vehicle has to stop somewhere.
virtual void activateReminders(const MSMoveReminder::Notification reason, const MSLane *enteredLane=0)
"Activates" all current move reminder
const MSStop & getNextStop() const
@ ROUTE_START_INVALID_PERMISSIONS
void addStops(const bool ignoreStopErrors, MSRouteIterator *searchStart=nullptr, bool addRouteStops=true)
Adds stops to the built vehicle.
SUMOVehicleClass getVClass() const
Returns the vehicle's access class.
MSParkingArea * getNextParkingArea()
get the upcoming parking area stop or nullptr
int myArrivalLane
The destination lane where the vehicle stops.
SUMOTime myDeparture
The real departure time.
bool isStoppedTriggered() const
Returns whether the vehicle is on a triggered stop.
void onDepart()
Called when the vehicle is inserted into the network.
virtual bool addTraciStop(SUMOVehicleParameter::Stop stop, std::string &errorMsg)
const MSRoute & getRoute() const
Returns the current route.
int getRoutePosition() const
return index of edge within route
bool replaceParkingArea(MSParkingArea *parkingArea, std::string &errorMsg)
replace the current parking area stop with a new stop with merge duration
static const SUMOTime NOT_YET_DEPARTED
bool myAmRegisteredAsWaiting
Whether this vehicle is registered as waiting for a person or container (for deadlock-recognition)
SUMOAbstractRouter< MSEdge, SUMOVehicle > & getRouterTT() const
returns the router according to the current routing mode of the vehicle
EnergyParams * myEnergyParams
The emission parameters this vehicle may have.
const SUMOVehicleParameter * myParameter
This vehicle's parameter.
int myRouteValidity
status of the current vehicle route
const MSVehicleType & getVehicleType() const
Returns the vehicle's type definition.
bool isStopped() const
Returns whether the vehicle is at a stop.
MSDevice * getDevice(const std::type_info &type) const
Returns a device of the given type if it exists, nullptr otherwise.
int myNumberReroutes
The number of reroutings.
double myArrivalPos
The position on the destination lane where the vehicle stops.
virtual void saveState(OutputDevice &out)
Saves the (common) state of a vehicle.
virtual void replaceVehicleType(const MSVehicleType *type)
Replaces the current vehicle type by the one given.
double myOdometer
A simple odometer to keep track of the length of the route already driven.
int getContainerNumber() const
Returns the number of containers.
bool replaceRouteEdges(ConstMSEdgeVector &edges, double cost, double savings, const std::string &info, bool onInit=false, bool check=false, bool removeStops=true, std::string *msgReturn=nullptr)
Replaces the current route by the given edges.
virtual void saveState(OutputDevice &out, const MSCFModel &cfm) const
Saves the vehicle variables.
Definition MSCFModel.cpp:76
The car-following model abstraction.
Definition MSCFModel.h:59
double estimateSpeedAfterDistance(const double dist, const double v, const double accel) const
virtual double maxNextSpeed(double speed, const MSVehicle *const veh) const
Returns the maximum speed given the current speed.
virtual double minNextSpeedEmergency(double speed, const MSVehicle *const veh=0) const
Returns the minimum speed after emergency braking, given the current speed (depends on the numerical ...
virtual VehicleVariables * createVehicleVariables() const
Returns model specific values which are stored inside a vehicle and must be used with casting.
Definition MSCFModel.h:268
double getEmergencyDecel() const
Get the vehicle type's maximal physically possible deceleration [m/s^2].
Definition MSCFModel.h:293
SUMOTime getStartupDelay() const
Get the vehicle type's startupDelay.
Definition MSCFModel.h:309
double getMinimalArrivalSpeed(double dist, double currentSpeed) const
Computes the minimal possible arrival speed after covering a given distance.
virtual void setHeadwayTime(double headwayTime)
Sets a new value for desired headway [s].
Definition MSCFModel.h:635
virtual double freeSpeed(const MSVehicle *const veh, double speed, double seen, double maxSpeed, const bool onInsertion=false, const CalcReason usage=CalcReason::CURRENT) const
Computes the vehicle's safe speed without a leader.
virtual double minNextSpeed(double speed, const MSVehicle *const veh=0) const
Returns the minimum speed given the current speed (depends on the numerical update scheme and its ste...
virtual double insertionFollowSpeed(const MSVehicle *const veh, double speed, double gap2pred, double predSpeed, double predMaxDecel, const MSVehicle *const pred=0) const
Computes the vehicle's safe speed (no dawdling) This method is used during the insertion stage....
SUMOTime getMinimalArrivalTime(double dist, double currentSpeed, double arrivalSpeed) const
Computes the minimal time needed to cover a distance given the desired speed at arrival.
virtual double finalizeSpeed(MSVehicle *const veh, double vPos) const
Applies interaction with stops and lane changing model influences. Called at most once per simulation...
virtual bool startupDelayStopped() const
whether startupDelay should be applied after stopping
Definition MSCFModel.h:360
@ FUTURE
the return value is used for calculating future speeds
Definition MSCFModel.h:99
@ CURRENT_WAIT
the return value is used for calculating junction stop speeds
Definition MSCFModel.h:101
virtual double maxNextSafeMin(double speed, const MSVehicle *const veh=0) const
Returns the maximum speed given the current speed and regarding driving dynamics.
Definition MSCFModel.h:391
double getApparentDecel() const
Get the vehicle type's apparent deceleration [m/s^2] (the one regarded by its followers.
Definition MSCFModel.h:301
double getMaxAccel() const
Get the vehicle type's maximum acceleration [m/s^2].
Definition MSCFModel.h:277
double brakeGap(const double speed) const
Returns the distance the vehicle needs to halt including driver's reaction time tau (i....
Definition MSCFModel.h:424
virtual double maximumLaneSpeedCF(const MSVehicle *const veh, double maxSpeed, double maxSpeedLane) const
Returns the maximum velocity the CF-model wants to achieve in the next step.
Definition MSCFModel.h:245
double maximumSafeStopSpeed(double gap, double decel, double currentSpeed, bool onInsertion=false, double headway=-1, bool relaxEmergency=true) const
Returns the maximum next velocity for stopping within gap.
double getMaxDecel() const
Get the vehicle type's maximal comfortable deceleration [m/s^2].
Definition MSCFModel.h:285
double getMinimalArrivalSpeedEuler(double dist, double currentSpeed) const
Computes the minimal possible arrival speed after covering a given distance for Euler update.
virtual double followSpeed(const MSVehicle *const veh, double speed, double gap2pred, double predSpeed, double predMaxDecel, const MSVehicle *const pred=0, const CalcReason usage=CalcReason::CURRENT) const =0
Computes the vehicle's follow speed (no dawdling)
double stopSpeed(const MSVehicle *const veh, const double speed, double gap, const CalcReason usage=CalcReason::CURRENT) const
Computes the vehicle's safe speed for approaching a non-moving obstacle (no dawdling)
Definition MSCFModel.h:189
virtual double getHeadwayTime() const
Get the driver's desired headway [s].
Definition MSCFModel.h:355
The ToC Device controls transition of control between automated and manual driving.
std::shared_ptr< MSSimpleDriverState > getDriverState() const
return internal state
void update()
update internal state
A device which collects info on the vehicle trip (mainly on departure and arrival)
double consumption(SUMOVehicle &veh, double a, double newSpeed)
return energy consumption in Wh (power multiplied by TS)
void setConsum(const double consumption)
double acceleration(SUMOVehicle &veh, double power, double oldSpeed)
double getConsum() const
Get consum.
A device which collects info on current friction Coefficient on the road.
A device which collects info on the vehicle trip (mainly on departure and arrival)
A device which collects info on the vehicle trip (mainly on departure and arrival)
void cancelCurrentCustomers()
remove the persons the taxi is currently waiting for from reservations
bool notifyMove(SUMOTrafficObject &veh, double oldPos, double newPos, double newSpeed)
Checks whether the vehicle is at a stop and transportable action is needed.
bool anyLeavingAtStop(const MSStop &stop) const
void transferAtSplitOrJoin(MSBaseVehicle *otherVeh)
transfers transportables that want to continue in the other train part (without boarding/loading dela...
void checkCollisionForInactive(MSLane *l)
trigger collision checking for inactive lane
A road/street connecting two junctions.
Definition MSEdge.h:78
static void clear()
Clears the dictionary.
Definition MSEdge.cpp:1163
static DepartLaneDefinition & getDefaultDepartLaneDefinition()
Definition MSEdge.h:821
const std::set< MSTransportable *, ComparatorNumericalIdLess > & getPersons() const
Returns this edge's persons set.
Definition MSEdge.h:205
const std::vector< MSLane * > & getLanes() const
Returns this edge's lanes.
Definition MSEdge.h:169
const MSEdge * getOppositeEdge() const
Returns the opposite direction edge if on exists else a nullptr.
Definition MSEdge.cpp:1423
bool isFringe() const
return whether this edge is at the fringe of the network
Definition MSEdge.h:786
const MSEdge * getNormalSuccessor() const
if this edge is an internal edge, return its first normal successor, otherwise the edge itself
Definition MSEdge.cpp:1017
const std::vector< MSLane * > * allowedLanes(const MSEdge &destination, SUMOVehicleClass vclass=SVC_IGNORING, bool ignoreTransientPermissions=false) const
Get the allowed lanes to reach the destination-edge.
Definition MSEdge.cpp:516
const MSEdge * getBidiEdge() const
return opposite superposable/congruent edge, if it exist and 0 else
Definition MSEdge.h:284
bool isNormal() const
return whether this edge is an internal edge
Definition MSEdge.h:265
double getSpeedLimit() const
Returns the speed limit of the edge @caution The speed limit of the first lane is returned; should pr...
Definition MSEdge.cpp:1235
bool hasChangeProhibitions(SUMOVehicleClass svc, int index) const
return whether this edge prohibits changing for the given vClass when starting on the given lane inde...
Definition MSEdge.cpp:1445
bool hasLaneChanger() const
Definition MSEdge.h:760
const MSJunction * getToJunction() const
Definition MSEdge.h:428
const MSJunction * getFromJunction() const
Definition MSEdge.h:424
int getNumLanes() const
Definition MSEdge.h:173
double getMinimumTravelTime(const SUMOVehicle *const veh) const
returns the minimum travel time for the given vehicle
Definition MSEdge.h:486
bool isRoundabout() const
Definition MSEdge.h:743
bool isInternal() const
return whether this edge is an internal edge
Definition MSEdge.h:270
double getWidth() const
Returns the edges's width (sum over all lanes)
Definition MSEdge.h:666
bool isVaporizing() const
Returns whether vehicles on this edge shall be vaporized.
Definition MSEdge.h:444
void addWaiting(SUMOVehicle *vehicle) const
Adds a vehicle to the list of waiting vehicles.
Definition MSEdge.cpp:1534
const MSEdge * getInternalFollowingEdge(const MSEdge *followerAfterInternal, SUMOVehicleClass vClass) const
Definition MSEdge.cpp:970
void removeWaiting(const SUMOVehicle *vehicle) const
Removes a vehicle from the list of waiting vehicles.
Definition MSEdge.cpp:1543
const MSEdgeVector & getSuccessors(SUMOVehicleClass vClass=SVC_IGNORING) const
Returns the following edges, restricted by vClass.
Definition MSEdge.cpp:1342
static bool gModelParkingManoeuver
whether parking simulation includes manoeuver time and any associated lane blocking
Definition MSGlobals.h:165
static bool gUseMesoSim
Definition MSGlobals.h:106
static bool gUseStopStarted
Definition MSGlobals.h:134
static bool gCheckRoutes
Definition MSGlobals.h:91
static SUMOTime gStartupWaitThreshold
The minimum waiting time before applying startupDelay.
Definition MSGlobals.h:183
static double gTLSYellowMinDecel
The minimum deceleration at a yellow traffic light (only overruled by emergencyDecel)
Definition MSGlobals.h:174
static double gLateralResolution
Definition MSGlobals.h:100
static bool gSemiImplicitEulerUpdate
Definition MSGlobals.h:53
static bool gSlopeCentered
whether to use a simplified slope computation (for compatibility with other simulations)
Definition MSGlobals.h:137
static bool gLefthand
Whether lefthand-drive is being simulated.
Definition MSGlobals.h:177
static bool gSublane
whether sublane simulation is enabled (sublane model or continuous lanechanging)
Definition MSGlobals.h:168
static SUMOTime gLaneChangeDuration
Definition MSGlobals.h:97
static bool gUseStopEnded
whether the simulation should replay previous stop times
Definition MSGlobals.h:133
static double gEmergencyDecelWarningThreshold
threshold for warning about strong deceleration
Definition MSGlobals.h:155
static bool gUsingInternalLanes
Information whether the simulation regards internal lanes.
Definition MSGlobals.h:81
void add(SUMOVehicle *veh)
Adds a single vehicle for departure.
virtual const MSJunctionLogic * getLogic() const
Definition MSJunction.h:141
virtual const MSLogicJunction::LinkBits & getResponseFor(int linkIndex) const
Returns the response for the given link.
Representation of a lane in the micro simulation.
Definition MSLane.h:84
std::vector< StopWatch< std::chrono::nanoseconds > > & getStopWatch()
Definition MSLane.h:1330
const std::vector< MSMoveReminder * > & getMoveReminders() const
Return the list of this lane's move reminders.
Definition MSLane.h:324
std::pair< const MSPerson *, double > nextBlocking(double minPos, double minRight, double maxLeft, double stopTime=0, bool bidi=false) const
This is just a wrapper around MSPModel::nextBlocking. You should always check using hasPedestrians be...
Definition MSLane.cpp:4677
MSLane * getParallelLane(int offset, bool includeOpposite=true) const
Returns the lane with the given offset parallel to this one or 0 if it does not exist.
Definition MSLane.cpp:2905
virtual MSVehicle * removeVehicle(MSVehicle *remVehicle, MSMoveReminder::Notification notification, bool notify=true)
Definition MSLane.cpp:2887
int getVehicleNumber() const
Returns the number of vehicles on this lane (for which this lane is responsible)
Definition MSLane.h:457
MSVehicle * getFirstAnyVehicle() const
returns the first vehicle that is fully or partially on this lane
Definition MSLane.cpp:2736
const MSLink * getEntryLink() const
Returns the entry link if this is an internal lane, else nullptr.
Definition MSLane.cpp:2824
int getVehicleNumberWithPartials() const
Returns the number of vehicles on this lane (including partial occupators)
Definition MSLane.h:465
double getBruttoVehLenSum() const
Returns the sum of lengths of vehicles, including their minGaps, which were on the lane during the la...
Definition MSLane.h:1193
std::pair< MSVehicle *const, double > getFollower(const MSVehicle *ego, double egoPos, double dist, MinorLinkMode mLinkMode, bool maxSearchDist=false) const
Find follower vehicle for the given ego vehicle (which may be on the opposite direction lane)
Definition MSLane.cpp:4482
static std::vector< MSLink * >::const_iterator succLinkSec(const SUMOVehicle &veh, int nRouteSuccs, const MSLane &succLinkSource, const std::vector< MSLane * > &conts)
Definition MSLane.cpp:2750
void markRecalculateBruttoSum()
Set a flag to recalculate the brutto (including minGaps) occupancy of this lane (used if mingap is ch...
Definition MSLane.cpp:2482
const MSLink * getLinkTo(const MSLane *const) const
returns the link to the given lane or nullptr, if it is not connected
Definition MSLane.cpp:2801
const MSLeaderInfo getLastVehicleInformation(const MSVehicle *ego, double latOffset, double minPos=0, bool allowCached=true, const MSVehicle *ignore=nullptr) const
Returns the last vehicles on the lane.
Definition MSLane.cpp:1488
MSLeaderDistanceInfo getFollowersOnConsecutive(const MSVehicle *ego, double backOffset, bool allSublanes, double searchDist=-1, MinorLinkMode mLinkMode=FOLLOW_ALWAYS, bool maxSearchDist=false) const
return the sublane followers with the largest missing rear gap among all predecessor lanes (within di...
Definition MSLane.cpp:3859
void forceVehicleInsertion(MSVehicle *veh, double pos, MSMoveReminder::Notification notification, double posLat=0)
Inserts the given vehicle at the given position.
Definition MSLane.cpp:1435
double getVehicleStopOffset(const MSVehicle *veh) const
Returns vehicle class specific stopOffset for the vehicle.
Definition MSLane.cpp:3834
double getSpeedLimit() const
Returns the lane's maximum allowed speed.
Definition MSLane.h:602
std::vector< MSVehicle * > VehCont
Container for vehicles.
Definition MSLane.h:119
const MSEdge * getNextNormal() const
Returns the lane's follower if it is an internal lane, the edge of the lane otherwise.
Definition MSLane.cpp:2514
SVCPermissions getPermissions() const
Returns the vehicle class permissions for this lane.
Definition MSLane.h:640
const std::vector< IncomingLaneInfo > & getIncomingLanes() const
Definition MSLane.h:984
MSLane * getCanonicalPredecessorLane() const
Definition MSLane.cpp:3327
double getLength() const
Returns the lane's length.
Definition MSLane.h:632
double getMaximumBrakeDist() const
compute maximum braking distance on this lane
Definition MSLane.cpp:2962
const MSLane * getInternalFollowingLane(const MSLane *const) const
returns the internal lane leading to the given lane or nullptr, if there is none
Definition MSLane.cpp:2813
std::pair< MSVehicle *const, double > getLeaderOnConsecutive(double dist, double seen, double speed, const MSVehicle &veh, const std::vector< MSLane * > &bestLaneConts, bool considerCrossingFoes=true) const
Returns the immediate leader and the distance to him.
Definition MSLane.cpp:3046
bool isLinkEnd(std::vector< MSLink * >::const_iterator &i) const
Definition MSLane.h:881
bool allowsVehicleClass(SUMOVehicleClass vclass) const
Definition MSLane.h:959
virtual double setPartialOccupation(MSVehicle *v)
Sets the information about a vehicle lapping into this lane.
Definition MSLane.cpp:386
double getVehicleMaxSpeed(const SUMOTrafficObject *const veh) const
Returns the lane's maximum speed, given a vehicle's speed limit adaptation.
Definition MSLane.h:575
double getRightSideOnEdge() const
Definition MSLane.h:1229
bool hasPedestrians() const
whether the lane has pedestrians on it
Definition MSLane.cpp:4670
int getIndex() const
Returns the lane's index.
Definition MSLane.h:668
MSLane * getCanonicalSuccessorLane() const
Definition MSLane.cpp:3351
double getOppositePos(double pos) const
return the corresponding position on the opposite lane
Definition MSLane.cpp:4477
MSLane * getLogicalPredecessorLane() const
get the most likely predecessor lane (sorted using by_connections_to_sorter). The result is cached in...
Definition MSLane.cpp:3271
double getCenterOnEdge() const
Definition MSLane.h:1237
bool isNormal() const
Definition MSLane.cpp:2675
MSVehicle * getLastAnyVehicle() const
returns the last vehicle that is fully or partially on this lane
Definition MSLane.cpp:2717
bool isInternal() const
Definition MSLane.cpp:2669
@ FOLLOW_NEVER
Definition MSLane.h:1008
virtual void resetPartialOccupation(MSVehicle *v)
Removes the information about a vehicle lapping into this lane.
Definition MSLane.cpp:405
SumoRNG * getRNG() const
return the associated RNG
Definition MSLane.h:246
MSLane * getOpposite() const
return the neighboring opposite direction lane for lane changing or nullptr
Definition MSLane.cpp:4465
virtual const VehCont & getVehiclesSecure() const
Returns the vehicles container; locks it for microsimulation.
Definition MSLane.h:484
virtual void releaseVehicles() const
Allows to use the container for microsimulation again.
Definition MSLane.h:514
bool mustCheckJunctionCollisions() const
whether this lane must check for junction collisions
Definition MSLane.cpp:4788
double interpolateLanePosToGeometryPos(double lanePos) const
Definition MSLane.h:555
MSLane * getBidiLane() const
retrieve bidirectional lane or nullptr
Definition MSLane.cpp:4782
@ COLLISION_ACTION_WARN
Definition MSLane.h:203
virtual const PositionVector & getShape(bool) const
Definition MSLane.h:294
MSLane * getParallelOpposite() const
return the opposite direction lane of this lanes edge or nullptr
Definition MSLane.cpp:4471
MSEdge & getEdge() const
Returns the lane's edge.
Definition MSLane.h:790
double getSpaceTillLastStanding(const MSVehicle *ego, bool &foundStopped) const
return the empty space up to the last standing vehicle or the empty space on the whole lane if no veh...
Definition MSLane.cpp:4797
const MSLane * getNormalPredecessorLane() const
get normal lane leading to this internal lane, for normal lanes, the lane itself is returned
Definition MSLane.cpp:3296
double getWidth() const
Returns the lane's width.
Definition MSLane.h:661
const std::vector< MSLink * > & getLinkCont() const
returns the container with all links !!!
Definition MSLane.h:750
MSVehicle * getFirstFullVehicle() const
returns the first vehicle for which this lane is responsible or 0
Definition MSLane.cpp:2708
const Position geometryPositionAtOffset(double offset, double lateralOffset=0) const
Definition MSLane.h:561
static CollisionAction getCollisionAction()
Definition MSLane.h:1401
saves leader/follower vehicles and their distances relative to an ego vehicle
virtual std::string toString() const
print a debugging representation
void fixOppositeGaps(bool isFollower)
subtract vehicle length from all gaps if the leader vehicle is driving in the opposite direction
virtual int addLeader(const MSVehicle *veh, double gap, double latOffset=0, int sublane=-1)
void setSublaneOffset(int offset)
set number of sublanes by which to shift positions
void removeOpposite(const MSLane *lane)
remove vehicles that are driving in the opposite direction (fully or partially) on the given lane
int numSublanes() const
virtual int addLeader(const MSVehicle *veh, bool beyond, double latOffset=0.)
virtual std::string toString() const
print a debugging representation
virtual void clear()
discard all information
bool hasVehicles() const
int getSublaneOffset() const
void getSubLanes(const MSVehicle *veh, double latOffset, int &rightmost, int &leftmost) const
Something on a lane to be noticed about vehicle movement.
Notification
Definition of a vehicle state.
@ NOTIFICATION_TELEPORT_ARRIVED
The vehicle was teleported out of the net.
@ NOTIFICATION_PARKING_REROUTE
The vehicle needs another parking area.
@ NOTIFICATION_DEPARTED
The vehicle has departed (was inserted into the network)
@ NOTIFICATION_LANE_CHANGE
The vehicle changes lanes (micro only)
@ NOTIFICATION_VAPORIZED_VAPORIZER
The vehicle got vaporized with a vaporizer.
@ NOTIFICATION_JUNCTION
The vehicle arrived at a junction.
@ NOTIFICATION_PARKING
The vehicle starts or ends parking.
@ NOTIFICATION_VAPORIZED_COLLISION
The vehicle got removed by a collision.
@ NOTIFICATION_LOAD_STATE
The vehicle has been loaded from a state file.
@ NOTIFICATION_TELEPORT
The vehicle is being teleported.
@ NOTIFICATION_TELEPORT_CONTINUATION
The vehicle continues being teleported past an edge.
The simulated network and simulation perfomer.
Definition MSNet.h:90
void removeVehicleStateListener(VehicleStateListener *listener)
Removes a vehicle states listener.
Definition MSNet.cpp:1393
VehicleState
Definition of a vehicle state.
Definition MSNet.h:637
@ STARTING_STOP
The vehicles starts to stop.
@ STARTING_PARKING
The vehicles starts to park.
@ STARTING_TELEPORT
The vehicle started to teleport.
@ ENDING_STOP
The vehicle ends to stop.
@ ARRIVED
The vehicle arrived at his destination (is deleted)
@ EMERGENCYSTOP
The vehicle had to brake harder than permitted.
@ MANEUVERING
Vehicle maneuvering either entering or exiting a parking space.
static MSNet * getInstance()
Returns the pointer to the unique instance of MSNet (singleton).
Definition MSNet.cpp:201
virtual MSTransportableControl & getContainerControl()
Returns the container control.
Definition MSNet.cpp:1326
std::string getStoppingPlaceID(const MSLane *lane, const double pos, const SumoXMLTag category) const
Returns the stop of the given category close to the given position.
Definition MSNet.cpp:1548
SUMOTime getCurrentTimeStep() const
Returns the current simulation step.
Definition MSNet.h:335
static bool hasInstance()
Returns whether the network was already constructed.
Definition MSNet.h:159
MSStoppingPlace * getStoppingPlace(const std::string &id, const SumoXMLTag category) const
Returns the named stopping place of the given category.
Definition MSNet.cpp:1527
void addVehicleStateListener(VehicleStateListener *listener)
Adds a vehicle states listener.
Definition MSNet.cpp:1385
bool hasContainers() const
Returns whether containers are simulated.
Definition MSNet.h:436
void informVehicleStateListener(const SUMOVehicle *const vehicle, VehicleState to, const std::string &info="")
Informs all added listeners about a vehicle's state change.
Definition MSNet.cpp:1402
bool hasPersons() const
Returns whether persons are simulated.
Definition MSNet.h:420
MSInsertionControl & getInsertionControl()
Returns the insertion control.
Definition MSNet.h:456
MSVehicleControl & getVehicleControl()
Returns the vehicle control.
Definition MSNet.h:403
virtual MSTransportableControl & getPersonControl()
Returns the person control.
Definition MSNet.cpp:1317
MSEdgeControl & getEdgeControl()
Returns the edge control.
Definition MSNet.h:446
bool hasInternalLinks() const
return whether the network contains internal links
Definition MSNet.h:812
bool hasElevation() const
return whether the network contains elevation data
Definition MSNet.h:822
static const double SAFETY_GAP
Definition MSPModel.h:59
A lane area vehicles can halt at.
int getOccupancyIncludingReservations(const SUMOVehicle *forVehicle) const
void enter(SUMOVehicle *veh, const bool parking) override
Called if a vehicle enters this stop.
void leaveFrom(SUMOVehicle *what) override
Called if a vehicle leaves this stop.
int getCapacity() const
Returns the area capacity.
int getLotIndex(const SUMOVehicle *veh) const
compute lot for this vehicle
int getLastFreeLotAngle() const
Return the angle of myLastFreeLot - the next parking lot only expected to be called after we have est...
bool parkOnRoad() const
whether vehicles park on the road
double getLastFreePosWithReservation(SUMOTime t, const SUMOVehicle &forVehicle, double brakePos)
Returns the last free position on this stop including reservations from the current lane and time ste...
double getLastFreeLotGUIAngle() const
Return the GUI angle of myLastFreeLot - the angle the GUI uses to rotate into the next parking lot as...
int getManoeuverAngle(const SUMOVehicle &forVehicle) const
Return the manoeuver angle of the lot where the vehicle is parked.
int getOccupancy() const
Returns the area occupancy.
double getGUIAngle(const SUMOVehicle &forVehicle) const
Return the GUI angle of the lot where the vehicle is parked.
void notifyApproach(const MSLink *link)
switch rail signal to active
static MSRailSignalControl & getInstance()
const ConstMSEdgeVector & getEdges() const
Definition MSRoute.h:128
const MSEdge * getLastEdge() const
returns the destination edge
Definition MSRoute.cpp:91
MSRouteIterator begin() const
Returns the begin of the list of edges to pass.
Definition MSRoute.cpp:73
const MSLane * lane
The lane to stop at (microsim only)
Definition MSStop.h:50
bool triggered
whether an arriving person lets the vehicle continue
Definition MSStop.h:69
bool containerTriggered
whether an arriving container lets the vehicle continue
Definition MSStop.h:71
SUMOTime timeToLoadNextContainer
The time at which the vehicle is able to load another container.
Definition MSStop.h:83
MSStoppingPlace * containerstop
(Optional) container stop if one is assigned to the stop
Definition MSStop.h:56
double getSpeed() const
return speed for passing waypoint / skipping on-demand stop
Definition MSStop.cpp:216
bool joinTriggered
whether coupling another vehicle (train) the vehicle continue
Definition MSStop.h:73
bool isOpposite
whether this an opposite-direction stop
Definition MSStop.h:87
SUMOTime getMinDuration(SUMOTime time) const
return minimum stop duration when starting stop at time
Definition MSStop.cpp:174
int numExpectedContainer
The number of still expected containers.
Definition MSStop.h:79
bool reached
Information whether the stop has been reached.
Definition MSStop.h:75
MSRouteIterator edge
The edge in the route to stop at.
Definition MSStop.h:48
SUMOTime timeToBoardNextPerson
The time at which the vehicle is able to board another person.
Definition MSStop.h:81
bool skipOnDemand
whether the decision to skip this stop has been made
Definition MSStop.h:89
const MSEdge * getEdge() const
Definition MSStop.cpp:58
double entryPos
the exact position when entering the stop (for state saving)
Definition MSStop.h:97
double getReachedThreshold() const
return startPos taking into account opposite stopping
Definition MSStop.cpp:68
SUMOTime endBoarding
the maximum time at which persons may board this vehicle
Definition MSStop.h:85
double getEndPos(const SUMOVehicle &veh) const
return halting position for upcoming stop;
Definition MSStop.cpp:39
int numExpectedPerson
The number of still expected persons.
Definition MSStop.h:77
MSParkingArea * parkingarea
(Optional) parkingArea if one is assigned to the stop
Definition MSStop.h:58
bool startedFromState
whether the 'started' value was loaded from simulaton state
Definition MSStop.h:91
MSStoppingPlace * chargingStation
(Optional) charging station if one is assigned to the stop
Definition MSStop.h:60
SUMOTime duration
The stopping duration.
Definition MSStop.h:67
SUMOTime getUntil() const
return until / ended time
Definition MSStop.cpp:191
const SUMOVehicleParameter::Stop pars
The stop parameter.
Definition MSStop.h:65
MSStoppingPlace * busstop
(Optional) bus stop if one is assigned to the stop
Definition MSStop.h:54
void stopBlocked(const SUMOVehicle *veh, SUMOTime time)
Definition MSStopOut.cpp:67
static bool active()
Definition MSStopOut.h:55
void stopNotStarted(const SUMOVehicle *veh)
Definition MSStopOut.cpp:76
void stopStarted(const SUMOVehicle *veh, int numPersons, int numContainers, SUMOTime time)
Definition MSStopOut.cpp:83
static MSStopOut * getInstance()
Definition MSStopOut.h:61
void stopEnded(const SUMOVehicle *veh, const MSStop &stop, bool simEnd=false)
double getBeginLanePosition() const
Returns the begin position of this stop.
virtual void enter(SUMOVehicle *veh, const bool parking)
Called if a vehicle enters this stop.
bool fits(double pos, const SUMOVehicle &veh) const
return whether the given vehicle fits at the given position
double getEndLanePosition() const
Returns the end position of this stop.
const MSLane & getLane() const
Returns the lane this stop is located at.
virtual void leaveFrom(SUMOVehicle *what)
Called if a vehicle leaves this stop.
bool hasAnyWaiting(const MSEdge *edge, SUMOVehicle *vehicle) const
check whether any transportables are waiting for the given vehicle
bool loadAnyWaiting(const MSEdge *edge, SUMOVehicle *vehicle, SUMOTime &timeToLoadNext, SUMOTime &stopDuration, MSTransportable *const force=nullptr)
load any applicable transportables Loads any person / container that is waiting on that edge for the ...
bool isPerson() const override
Whether it is a person.
A static instance of this class in GapControlState deactivates gap control for vehicles whose referen...
Definition MSVehicle.h:1361
void vehicleStateChanged(const SUMOVehicle *const vehicle, MSNet::VehicleState to, const std::string &info="")
Called if a vehicle changes its state.
Changes the wished vehicle speed / lanes.
Definition MSVehicle.h:1356
void setLaneChangeMode(int value)
Sets lane changing behavior.
TraciLaneChangePriority myTraciLaneChangePriority
flags for determining the priority of traci lane change requests
Definition MSVehicle.h:1687
bool getEmergencyBrakeRedLight() const
Returns whether red lights shall be a reason to brake.
Definition MSVehicle.h:1530
SUMOTime getLaneTimeLineEnd()
void adaptLaneTimeLine(int indexShift)
Adapts lane timeline when moving to a new lane and the lane index changes.
void setRemoteControlled(Position xyPos, MSLane *l, double pos, double posLat, double angle, int edgeOffset, const ConstMSEdgeVector &route, SUMOTime t)
bool isRemoteAffected(SUMOTime t) const
int getSpeedMode() const
return the current speed mode
void deactivateGapController()
Deactivates the gap control.
Influencer()
Constructor.
void setSpeedMode(int speedMode)
Sets speed-constraining behaviors.
std::shared_ptr< GapControlState > myGapControlState
The gap control state.
Definition MSVehicle.h:1632
int getSignals() const
Definition MSVehicle.h:1603
bool myConsiderMaxDeceleration
Whether the maximum deceleration shall be regarded.
Definition MSVehicle.h:1653
void setLaneTimeLine(const std::vector< std::pair< SUMOTime, int > > &laneTimeLine)
Sets a new lane timeline.
bool hasSpeedTimeLine(SUMOTime t) const
Definition MSVehicle.h:1437
bool myRespectJunctionLeaderPriority
Whether the junction priority rules are respected (within)
Definition MSVehicle.h:1662
void setOriginalSpeed(double speed)
Stores the originally longitudinal speed.
double myOriginalSpeed
The velocity before influence.
Definition MSVehicle.h:1635
bool myConsiderSpeedLimit
Whether the speed limit shall be regarded.
Definition MSVehicle.h:1647
double implicitDeltaPosRemote(const MSVehicle *veh)
return the change in longitudinal position that is implicit in the new remote position
double implicitSpeedRemote(const MSVehicle *veh, double oldSpeed)
return the speed that is implicit in the new remote position
void postProcessRemoteControl(MSVehicle *v)
update position from remote control
double gapControlSpeed(SUMOTime currentTime, const SUMOVehicle *veh, double speed, double vSafe, double vMin, double vMax)
Applies gap control logic on the speed.
void setSublaneChange(double latDist)
Sets a new sublane-change request.
double getOriginalSpeed() const
Returns the originally longitudinal speed to use.
SUMOTime myLastRemoteAccess
Definition MSVehicle.h:1671
bool getRespectJunctionLeaderPriority() const
Returns whether junction priority rules within the junction shall be respected (concerns vehicles wit...
Definition MSVehicle.h:1538
LaneChangeMode myStrategicLC
lane changing which is necessary to follow the current route
Definition MSVehicle.h:1676
LaneChangeMode mySpeedGainLC
lane changing to travel with higher speed
Definition MSVehicle.h:1680
void init()
Static initalization.
LaneChangeMode mySublaneLC
changing to the prefered lateral alignment
Definition MSVehicle.h:1684
bool getRespectJunctionPriority() const
Returns whether junction priority rules shall be respected (concerns approaching vehicles outside the...
Definition MSVehicle.h:1522
static void cleanup()
Static cleanup.
int getLaneChangeMode() const
return the current lane change mode
SUMOTime getLaneTimeLineDuration()
double influenceSpeed(SUMOTime currentTime, double speed, double vSafe, double vMin, double vMax)
Applies stored velocity information on the speed to use.
double changeRequestRemainingSeconds(const SUMOTime currentTime) const
Return the remaining number of seconds of the current laneTimeLine assuming one exists.
bool myConsiderSafeVelocity
Whether the safe velocity shall be regarded.
Definition MSVehicle.h:1644
bool mySpeedAdaptationStarted
Whether influencing the speed has already started.
Definition MSVehicle.h:1641
~Influencer()
Destructor.
void setSignals(int signals)
Definition MSVehicle.h:1599
double myLatDist
The requested lateral change.
Definition MSVehicle.h:1638
bool considerSpeedLimit() const
Returns whether speed limits shall be considered.
Definition MSVehicle.h:1549
bool myEmergencyBrakeRedLight
Whether red lights are a reason to brake.
Definition MSVehicle.h:1659
LaneChangeMode myRightDriveLC
changing to the rightmost lane
Definition MSVehicle.h:1682
void setSpeedTimeLine(const std::vector< std::pair< SUMOTime, double > > &speedTimeLine)
Sets a new velocity timeline.
void updateRemoteControlRoute(MSVehicle *v)
update route if provided by remote control
bool considerMaxDeceleration() const
Returns whether safe velocities shall be considered.
Definition MSVehicle.h:1555
SUMOTime getLastAccessTimeStep() const
Definition MSVehicle.h:1579
bool myConsiderMaxAcceleration
Whether the maximum acceleration shall be regarded.
Definition MSVehicle.h:1650
LaneChangeMode myCooperativeLC
lane changing with the intent to help other vehicles
Definition MSVehicle.h:1678
bool isRemoteControlled() const
bool myRespectJunctionPriority
Whether the junction priority rules are respected (approaching)
Definition MSVehicle.h:1656
int influenceChangeDecision(const SUMOTime currentTime, const MSEdge &currentEdge, const int currentLaneIndex, int state)
Applies stored LaneChangeMode information and laneTimeLine.
void activateGapController(double originalTau, double newTimeHeadway, double newSpaceHeadway, double duration, double changeRate, double maxDecel, MSVehicle *refVeh=nullptr)
Activates the gap control with the given parameters,.
Container for manouevering time associated with stopping.
Definition MSVehicle.h:1280
SUMOTime myManoeuvreCompleteTime
Time at which this manoeuvre should complete.
Definition MSVehicle.h:1332
MSVehicle::ManoeuvreType getManoeuvreType() const
Accessor (get) for manoeuvre type.
std::string myManoeuvreStop
The name of the stop associated with the Manoeuvre - for debug output.
Definition MSVehicle.h:1326
bool manoeuvreIsComplete() const
Check if any manoeuver is ongoing and whether the completion time is beyond currentTime.
bool configureExitManoeuvre(MSVehicle *veh)
Setup the myManoeuvre for exiting (Sets completion time and manoeuvre type)
void setManoeuvreType(const MSVehicle::ManoeuvreType mType)
Accessor (set) for manoeuvre type.
Manoeuvre & operator=(const Manoeuvre &manoeuvre)
Assignment operator.
Manoeuvre()
Constructor.
ManoeuvreType myManoeuvreType
Manoeuvre type - currently entry, exit or none.
Definition MSVehicle.h:1335
double getGUIIncrement() const
Accessor for GUI rotation step when parking (radians)
SUMOTime myManoeuvreStartTime
Time at which the Manoeuvre for this stop started.
Definition MSVehicle.h:1329
bool operator!=(const Manoeuvre &manoeuvre)
Operator !=.
bool entryManoeuvreIsComplete(MSVehicle *veh)
Configure an entry manoeuvre if nothing is configured - otherwise check if complete.
bool manoeuvreIsComplete(const ManoeuvreType checkType) const
Check if specific manoeuver is ongoing and whether the completion time is beyond currentTime.
bool configureEntryManoeuvre(MSVehicle *veh)
Setup the entry manoeuvre for this vehicle (Sets completion time and manoeuvre type)
Container that holds the vehicles driving state (position+speed).
Definition MSVehicle.h:87
double myPosLat
the stored lateral position
Definition MSVehicle.h:140
State(double pos, double speed, double posLat, double backPos, double previousSpeed)
Constructor.
double myPreviousSpeed
the speed at the begin of the previous time step
Definition MSVehicle.h:148
double myPos
the stored position
Definition MSVehicle.h:134
bool operator!=(const State &state)
Operator !=.
double myLastCoveredDist
Definition MSVehicle.h:154
double mySpeed
the stored speed (should be >=0 at any time)
Definition MSVehicle.h:137
State & operator=(const State &state)
Assignment operator.
double pos() const
Position of this state.
Definition MSVehicle.h:107
double myBackPos
the stored back position
Definition MSVehicle.h:145
void passTime(SUMOTime dt, bool waiting)
const std::string getState() const
SUMOTime cumulatedWaitingTime(SUMOTime memory=-1) const
void setState(const std::string &state)
WaitingTimeCollector(SUMOTime memory=MSGlobals::gWaitingTimeMemory)
Constructor.
void registerEmergencyStop()
register emergency stop
SUMOVehicle * getVehicle(const std::string &id) const
Returns the vehicle with the given id.
void registerStopEnded()
register emergency stop
void registerEmergencyBraking()
register emergency stop
void removeVType(const MSVehicleType *vehType)
void registerOneWaiting()
increases the count of vehicles waiting for a transport to allow recognition of person / container re...
void unregisterOneWaiting()
decreases the count of vehicles waiting for a transport to allow recognition of person / container re...
void registerStopStarted()
register emergency stop
Abstract in-vehicle device.
Representation of a vehicle in the micro simulation.
Definition MSVehicle.h:77
void setManoeuvreType(const MSVehicle::ManoeuvreType mType)
accessor function to myManoeuvre equivalent
TraciLaneChangePriority
modes for prioritizing traci lane change requests
Definition MSVehicle.h:1158
@ LCP_OPPORTUNISTIC
Definition MSVehicle.h:1162
double getRightSideOnEdge(const MSLane *lane=0) const
Get the vehicle's lateral position on the edge of the given lane (or its current edge if lane == 0)
bool wasRemoteControlled(SUMOTime lookBack=DELTA_T) const
Returns the information whether the vehicle is fully controlled via TraCI within the lookBack time.
void processLinkApproaches(double &vSafe, double &vSafeMin, double &vSafeMinDist)
This method iterates through the driveprocess items for the vehicle and adapts the given in/out param...
const MSLane * getPreviousLane(const MSLane *current, int &furtherIndex) const
void checkLinkLeader(const MSLink *link, const MSLane *lane, double seen, DriveProcessItem *const lastLink, double &v, double &vLinkPass, double &vLinkWait, bool &setRequest, bool isShadowLink=false) const
checks for link leaders on the given link
void checkRewindLinkLanes(const double lengthsInFront, DriveItemVector &lfLinks) const
runs heuristic for keeping the intersection clear in case of downstream jamming
bool willStop() const
Returns whether the vehicle will stop on the current edge.
bool hasDriverState() const
Whether this vehicle is equipped with a MSDriverState.
Definition MSVehicle.h:1000
static int nextLinkPriority(const std::vector< MSLane * > &conts)
get a numerical value for the priority of the upcoming link
double getTimeGapOnLane() const
Returns the time gap in seconds to the leader of the vehicle on the same lane.
void updateBestLanes(bool forceRebuild=false, const MSLane *startLane=0)
computes the best lanes to use in order to continue the route
bool myAmIdling
Whether the vehicle is trying to enter the network (eg after parking so engine is running)
Definition MSVehicle.h:1949
SUMOTime myWaitingTime
The time the vehicle waits (is not faster than 0.1m/s) in seconds.
Definition MSVehicle.h:1885
double getStopDelay() const
Returns the public transport stop delay in seconds.
double computeAngle() const
compute the current vehicle angle
double myTimeLoss
the time loss in seconds due to driving with less than maximum speed
Definition MSVehicle.h:1889
SUMOTime myLastActionTime
Action offset (actions are taken at time myActionOffset + N*getActionStepLength()) Initialized to 0,...
Definition MSVehicle.h:1904
ConstMSEdgeVector::const_iterator getRerouteOrigin() const
Returns the starting point for reroutes (usually the current edge)
bool hasArrivedInternal(bool oppositeTransformed=true) const
Returns whether this vehicle has already arived (reached the arrivalPosition on its final edge) metho...
double getFriction() const
Returns the current friction on the road as perceived by the friction device.
bool ignoreFoe(const SUMOTrafficObject *foe) const
decide whether a given foe object may be ignored
void boardTransportables(MSStop &stop)
board persons and load transportables at the given stop
const std::vector< const MSLane * > getUpcomingLanesUntil(double distance) const
Returns the upcoming (best followed by default 0) sequence of lanes to continue the route starting at...
double getCurveRadius() const
Returns the vehicle's current curve radius in m.
bool isOnRoad() const
Returns the information whether the vehicle is on a road (is simulated)
Definition MSVehicle.h:605
void adaptLaneEntering2MoveReminder(const MSLane &enteredLane)
Adapts the vehicle's entering of a new lane.
void addTransportable(MSTransportable *transportable)
Adds a person or container to this vehicle.
SUMOTime myJunctionConflictEntryTime
Definition MSVehicle.h:1974
double getLeftSideOnEdge(const MSLane *lane=0) const
Get the vehicle's lateral position on the edge of the given lane (or its current edge if lane == 0)
PositionVector getBoundingPoly(double offset=0) const
get bounding polygon
void setTentativeLaneAndPosition(MSLane *lane, double pos, double posLat=0)
set tentative lane and position during insertion to ensure that all cfmodels work (some of them requi...
bool brakeForOverlap(const MSLink *link, const MSLane *lane) const
handle width transitions
void workOnMoveReminders(double oldPos, double newPos, double newSpeed)
Processes active move reminder.
bool isStoppedOnLane() const
double getDistanceToPosition(double destPos, const MSLane *destLane) const
bool brokeDown() const
Returns how long the vehicle has been stopped already due to lack of energy.
double myAcceleration
The current acceleration after dawdling in m/s.
Definition MSVehicle.h:1931
void registerInsertionApproach(MSLink *link, double dist)
register approach on insertion
void cleanupFurtherLanes()
remove vehicle from further lanes (on leaving the network)
void adaptToLeaders(const MSLeaderInfo &ahead, double latOffset, const double seen, DriveProcessItem *const lastLink, const MSLane *const lane, double &v, double &vLinkPass) const
const MSLane * getBackLane() const
Returns the lane the where the rear of the object is currently at.
void enterLaneAtInsertion(MSLane *enteredLane, double pos, double speed, double posLat, MSMoveReminder::Notification notification)
Update when the vehicle enters a new lane in the emit step.
double getBackPositionOnLane() const
Get the vehicle's position relative to its current lane.
Definition MSVehicle.h:405
double myStopSpeed
the speed that is needed for a scheduled stop or waypoint
Definition MSVehicle.h:1964
void setPreviousSpeed(double prevSpeed, double prevAcceleration)
Sets the influenced previous speed.
double myRawAngle
the angle in radians before lane changing
Definition MSVehicle.h:1956
SUMOTime getArrivalTime(SUMOTime t, double seen, double v, double arrivalSpeed) const
double getAccumulatedWaitingSeconds() const
Returns the number of seconds waited (speed was lesser than 0.1m/s) within the last millisecs.
Definition MSVehicle.h:714
SUMOTime getWaitingTime(const bool accumulated=false) const
Returns the SUMOTime waited (speed was lesser than 0.1m/s)
Definition MSVehicle.h:670
bool isFrontOnLane(const MSLane *lane) const
Returns the information whether the front of the vehicle is on the given lane.
virtual ~MSVehicle()
Destructor.
void processLaneAdvances(std::vector< MSLane * > &passedLanes, std::string &emergencyReason)
This method checks if the vehicle has advanced over one or several lanes along its route and triggers...
MSAbstractLaneChangeModel & getLaneChangeModel()
void setEmergencyBlueLight(SUMOTime currentTime)
sets the blue flashing light for emergency vehicles
bool isActionStep(SUMOTime t) const
Returns whether the next simulation step will be an action point for the vehicle.
Definition MSVehicle.h:635
MSAbstractLaneChangeModel * myLaneChangeModel
Definition MSVehicle.h:1911
Position getPositionAlongBestLanes(double offset) const
Return the (x,y)-position, which the vehicle would reach if it continued along its best continuation ...
bool hasValidRouteStart(std::string &msg)
checks whether the vehicle can depart on the first edge
double getLeftSideOnLane() const
Get the lateral position of the vehicles left side on the lane:
std::vector< MSLane * > myFurtherLanes
The information into which lanes the vehicle laps into.
Definition MSVehicle.h:1938
bool signalSet(int which) const
Returns whether the given signal is on.
Definition MSVehicle.h:1194
MSCFModel::VehicleVariables * myCFVariables
The per vehicle variables of the car following model.
Definition MSVehicle.h:2186
bool betterContinuation(const LaneQ *bestConnectedNext, const LaneQ &m) const
comparison between different continuations from the same lane
bool addTraciStop(SUMOVehicleParameter::Stop stop, std::string &errorMsg)
void checkLinkLeaderCurrentAndParallel(const MSLink *link, const MSLane *lane, double seen, DriveProcessItem *const lastLink, double &v, double &vLinkPass, double &vLinkWait, bool &setRequest) const
checks for link leaders of the current link as well as the parallel link (if there is one)
std::pair< double, const MSLink * > myNextTurn
the upcoming turn for the vehicle
Definition MSVehicle.h:1935
double getDistanceToLeaveJunction() const
get the distance from the start of this lane to the start of the next normal lane (or 0 if this lane ...
int influenceChangeDecision(int state)
allow TraCI to influence a lane change decision
double getMaxSpeedOnLane() const
Returns the maximal speed for the vehicle on its current lane (including speed factor and deviation,...
bool isRemoteControlled() const
Returns the information whether the vehicle is fully controlled via TraCI.
bool myAmOnNet
Whether the vehicle is on the network (not parking, teleported, vaporized, or arrived)
Definition MSVehicle.h:1946
void enterLaneAtMove(MSLane *enteredLane, bool onTeleporting=false)
Update when the vehicle enters a new lane in the move step.
double myLastAngle
the angle in radians from the previous simulation step (for computing curve radius)
Definition MSVehicle.h:1958
void adaptBestLanesOccupation(int laneIndex, double density)
update occupation from MSLaneChanger
std::pair< double, double > estimateTimeToNextStop() const
return time (s) and distance to the next stop
double accelThresholdForWaiting() const
maximum acceleration to consider a vehicle as 'waiting' at low speed
Definition MSVehicle.h:2100
void setAngle(double angle, bool straightenFurther=false)
Set a custom vehicle angle in rad, optionally updates furtherLanePosLat.
std::vector< LaneQ >::iterator myCurrentLaneInBestLanes
Definition MSVehicle.h:1926
void setApproachingForAllLinks()
Register junction approaches for all link items in the current plan.
double getDeltaPos(const double accel) const
calculates the distance covered in the next integration step given an acceleration and assuming the c...
const MSLane * myLastBestLanesInternalLane
Definition MSVehicle.h:1914
void updateOccupancyAndCurrentBestLane(const MSLane *startLane)
updates LaneQ::nextOccupation and myCurrentLaneInBestLanes
const std::vector< MSLane * > getUpstreamOppositeLanes() const
Returns the sequence of opposite lanes corresponding to past lanes.
WaitingTimeCollector myWaitingTimeCollector
Definition MSVehicle.h:1886
void setRemoteState(Position xyPos)
sets position outside the road network
void fixPosition()
repair errors in vehicle position after changing between internal edges
double getAcceleration() const
Returns the vehicle's acceleration in m/s (this is computed as the last step's mean acceleration in c...
Definition MSVehicle.h:514
double getSpeedWithoutTraciInfluence() const
Returns the uninfluenced velocity.
PositionVector getBoundingBox(double offset=0) const
get bounding rectangle
ManoeuvreType
flag identifying which, if any, manoeuvre is in progress
Definition MSVehicle.h:1253
@ MANOEUVRE_ENTRY
Manoeuvre into stopping place.
Definition MSVehicle.h:1255
@ MANOEUVRE_NONE
not manouevring
Definition MSVehicle.h:1259
@ MANOEUVRE_EXIT
Manoeuvre out of stopping place.
Definition MSVehicle.h:1257
const MSEdge * getNextEdgePtr() const
returns the next edge (possibly an internal edge)
Position getPosition(const double offset=0) const
Return current position (x/y, cartesian)
void setBrakingSignals(double vNext)
sets the braking lights on/off
const std::vector< MSLane * > & getBestLanesContinuation() const
Returns the best sequence of lanes to continue the route starting at myLane.
const MSEdge * myLastBestLanesEdge
Definition MSVehicle.h:1913
bool ignoreCollision() const
whether this vehicle is except from collision checks
Influencer * myInfluencer
An instance of a velocity/lane influencing instance; built in "getInfluencer".
Definition MSVehicle.h:2189
void saveState(OutputDevice &out)
Saves the states of a vehicle.
void onRemovalFromNet(const MSMoveReminder::Notification reason)
Called when the vehicle is removed from the network.
void planMove(const SUMOTime t, const MSLeaderInfo &ahead, const double lengthsInFront)
Compute safe velocities for the upcoming lanes based on positions and speeds from the last time step....
bool resumeFromStopping()
int getBestLaneOffset() const
void adaptToJunctionLeader(const std::pair< const MSVehicle *, double > leaderInfo, const double seen, DriveProcessItem *const lastLink, const MSLane *const lane, double &v, double &vLinkPass, double distToCrossing=-1) const
double lateralDistanceToLane(const int offset) const
Get the minimal lateral distance required to move fully onto the lane at given offset.
double getBackPositionOnLane(const MSLane *lane) const
Get the vehicle's position relative to the given lane.
Definition MSVehicle.h:398
void leaveLaneBack(const MSMoveReminder::Notification reason, const MSLane *leftLane)
Update of reminders if vehicle back leaves a lane during (during forward movement.
void resetActionOffset(const SUMOTime timeUntilNextAction=0)
Resets the action offset for the vehicle.
std::vector< DriveProcessItem > DriveItemVector
Container for used Links/visited Lanes during planMove() and executeMove.
Definition MSVehicle.h:2043
void interpolateLateralZ(Position &pos, double offset, double posLat) const
perform lateral z interpolation in elevated networks
void setBlinkerInformation()
sets the blue flashing light for emergency vehicles
const MSEdge * getCurrentEdge() const
Returns the edge the vehicle is currently at (possibly an internal edge or nullptr)
void adaptToLeaderDistance(const MSLeaderDistanceInfo &ahead, double latOffset, double seen, DriveProcessItem *const lastLink, double &v, double &vLinkPass) const
DriveItemVector::iterator myNextDriveItem
iterator pointing to the next item in myLFLinkLanes
Definition MSVehicle.h:2056
bool unsafeLinkAhead(const MSLane *lane, double zipperDist) const
whether the vehicle may safely move to the given lane with regard to upcoming links
void leaveLane(const MSMoveReminder::Notification reason, const MSLane *approachedLane=0)
Update of members if vehicle leaves a new lane in the lane change step or at arrival.
const MSLink * myHaveStoppedFor
Definition MSVehicle.h:1978
bool isIdling() const
Returns whether a sim vehicle is waiting to enter a lane (after parking has completed)
Definition MSVehicle.h:621
std::shared_ptr< MSSimpleDriverState > getDriverState() const
Returns the vehicle driver's state.
void removeApproachingInformation(const DriveItemVector &lfLinks) const
unregister approach from all upcoming links
double getAngleDiff() const
get the change in angle from the last simulation step
SUMOTime myJunctionEntryTimeNeverYield
Definition MSVehicle.h:1973
double getLatOffset(const MSLane *lane) const
Get the offset that that must be added to interpret myState.myPosLat for the given lane.
bool rerouteParkingArea(const std::string &parkingAreaID, std::string &errorMsg)
bool hasArrived() const
Returns whether this vehicle has already arrived (reached the arrivalPosition on its final edge)
void switchOffSignal(int signal)
Switches the given signal off.
Definition MSVehicle.h:1177
double getStopArrivalDelay() const
Returns the estimated public transport stop arrival delay in seconds.
int mySignals
State of things of the vehicle that can be on or off.
Definition MSVehicle.h:1943
bool setExitManoeuvre()
accessor function to myManoeuvre equivalent
bool isOppositeLane(const MSLane *lane) const
whether the give lane is reverse direction of the current route or not
double myStopDist
distance to the next stop or doubleMax if there is none
Definition MSVehicle.h:1961
Signalling
Some boolean values which describe the state of some vehicle parts.
Definition MSVehicle.h:1112
@ VEH_SIGNAL_BLINKER_RIGHT
Right blinker lights are switched on.
Definition MSVehicle.h:1116
@ VEH_SIGNAL_BRAKELIGHT
The brake lights are on.
Definition MSVehicle.h:1122
@ VEH_SIGNAL_EMERGENCY_BLUE
A blue emergency light is on.
Definition MSVehicle.h:1138
@ VEH_SIGNAL_BLINKER_LEFT
Left blinker lights are switched on.
Definition MSVehicle.h:1118
SUMOTime getActionStepLength() const
Returns the vehicle's action step length in millisecs, i.e. the interval between two action points.
Definition MSVehicle.h:525
bool myHaveToWaitOnNextLink
Definition MSVehicle.h:1951
SUMOTime collisionStopTime() const
Returns the remaining time a vehicle needs to stop due to a collision. A negative value indicates tha...
const std::vector< const MSLane * > getPastLanesUntil(double distance) const
Returns the sequence of past lanes (right-most on edge) based on the route starting at the current la...
double getBestLaneDist() const
returns the distance that can be driven without lane change
void replaceVehicleType(const MSVehicleType *type)
Replaces the current vehicle type by the one given.
void updateState(double vNext, bool parking=false)
updates the vehicles state, given a next value for its speed. This value can be negative in case of t...
double slowDownForSchedule(double vMinComfortable) const
optionally return an upper bound on speed to stay within the schedule
bool executeMove()
Executes planned vehicle movements with regards to right-of-way.
const MSLane * getLane() const
Returns the lane the vehicle is on.
Definition MSVehicle.h:581
std::pair< const MSVehicle *const, double > getFollower(double dist=0) const
Returns the follower of the vehicle looking for a fixed distance.
SUMOTime getWaitingTimeFor(const MSLink *link) const
getWaitingTime, but taking into account having stopped for a stop-link
ChangeRequest
Requests set via TraCI.
Definition MSVehicle.h:191
@ REQUEST_HOLD
vehicle want's to keep the current lane
Definition MSVehicle.h:199
@ REQUEST_LEFT
vehicle want's to change to left lane
Definition MSVehicle.h:195
@ REQUEST_NONE
vehicle doesn't want to change
Definition MSVehicle.h:193
@ REQUEST_RIGHT
vehicle want's to change to right lane
Definition MSVehicle.h:197
bool isLeader(const MSLink *link, const MSVehicle *veh, const double gap) const
whether the given vehicle must be followed at the given junction
void resetApproachOnReroute()
reset rail signal approach information
void computeFurtherLanes(MSLane *enteredLane, double pos, bool collision=false)
updates myFurtherLanes on lane insertion or after collision
MSLane * getMutableLane() const
Returns the lane the vehicle is on Non const version indicates that something volatile is going on.
Definition MSVehicle.h:589
std::pair< const MSLane *, double > getLanePosAfterDist(double distance) const
return lane and position along bestlanes at the given distance
SUMOTime myCollisionImmunity
amount of time for which the vehicle is immune from collisions
Definition MSVehicle.h:1967
bool passingMinor() const
decide whether the vehicle is passing a minor link or has comitted to do so
void updateWaitingTime(double vNext)
Updates the vehicle's waiting time counters (accumulated and consecutive)
void enterLaneAtLaneChange(MSLane *enteredLane)
Update when the vehicle enters a new lane in the laneChange step.
BaseInfluencer & getBaseInfluencer()
Returns the velocity/lane influencer.
Influencer & getInfluencer()
bool isBidiOn(const MSLane *lane) const
whether this vehicle is driving against lane
double getRightSideOnLane() const
Get the lateral position of the vehicles right side on the lane:
double getCurrentApparentDecel() const
get apparent deceleration based on vType parameters and current acceleration
double updateFurtherLanes(std::vector< MSLane * > &furtherLanes, std::vector< double > &furtherLanesPosLat, const std::vector< MSLane * > &passedLanes)
update a vector of further lanes and return the new backPos
DriveItemVector myLFLinkLanesPrev
planned speeds from the previous step for un-registering from junctions after the new container is fi...
Definition MSVehicle.h:2049
std::vector< std::vector< LaneQ > > myBestLanes
Definition MSVehicle.h:1921
void setActionStepLength(double actionStepLength, bool resetActionOffset=true)
Sets the action steplength of the vehicle.
double getLateralPositionOnLane() const
Get the vehicle's lateral position on the lane.
Definition MSVehicle.h:413
double getSlope() const
Returns the slope of the road at vehicle's position in degrees.
bool myActionStep
The flag myActionStep indicates whether the current time step is an action point for the vehicle.
Definition MSVehicle.h:1901
const Position getBackPosition() const
bool congested() const
void loadState(const SUMOSAXAttributes &attrs, const SUMOTime offset)
Loads the state of this vehicle from the given description.
SUMOTime myTimeSinceStartup
duration of driving (speed > SUMO_const_haltingSpeed) after the last halting episode
Definition MSVehicle.h:1977
double getSpeed() const
Returns the vehicle's current speed.
Definition MSVehicle.h:490
SUMOTime remainingStopDuration() const
Returns the remaining stop duration for a stopped vehicle or 0.
bool keepStopping(bool afterProcessing=false) const
Returns whether the vehicle is stopped and must continue to do so.
void workOnIdleReminders()
cycle through vehicle devices invoking notifyIdle
static std::vector< MSLane * > myEmptyLaneVector
Definition MSVehicle.h:1928
Position myCachedPosition
Definition MSVehicle.h:1969
bool replaceRoute(ConstMSRoutePtr route, const std::string &info, bool onInit=false, int offset=0, bool addStops=true, bool removeStops=true, std::string *msgReturn=nullptr)
Replaces the current route by the given one.
MSVehicle::ManoeuvreType getManoeuvreType() const
accessor function to myManoeuvre equivalent
double checkReversal(bool &canReverse, double speedThreshold=SUMO_const_haltingSpeed, double seen=0) const
void updateLaneBruttoSum()
Update the lane brutto occupancy after a change in minGap.
void removePassedDriveItems()
Erase passed drive items from myLFLinkLanes (and unregister approaching information for corresponding...
const std::vector< MSLane * > & getFurtherLanes() const
Definition MSVehicle.h:839
const std::vector< LaneQ > & getBestLanes() const
Returns the description of best lanes to use in order to continue the route.
std::vector< double > myFurtherLanesPosLat
lateral positions on further lanes
Definition MSVehicle.h:1940
bool checkActionStep(const SUMOTime t)
Returns whether the vehicle is supposed to take action in the current simulation step Updates myActio...
const MSCFModel & getCarFollowModel() const
Returns the vehicle's car following model definition.
Definition MSVehicle.h:973
Position validatePosition(Position result, double offset=0) const
ensure that a vehicle-relative position is not invalid
void loadPreviousApproaching(MSLink *link, bool setRequest, SUMOTime arrivalTime, double arrivalSpeed, double arrivalSpeedBraking, double dist, double leaveSpeed)
bool keepClear(const MSLink *link) const
decide whether the given link must be kept clear
bool manoeuvreIsComplete() const
accessor function to myManoeuvre equivalent
double processNextStop(double currentVelocity)
Processes stops, returns the velocity needed to reach the stop.
double myAngle
the angle in radians (
Definition MSVehicle.h:1954
bool ignoreRed(const MSLink *link, bool canBrake) const
decide whether a red (or yellow light) may be ignored
double getPositionOnLane() const
Get the vehicle's position along the lane.
Definition MSVehicle.h:374
void updateTimeLoss(double vNext)
Updates the vehicle's time loss.
MSDevice_DriverState * myDriverState
This vehicle's driver state.
Definition MSVehicle.h:1895
bool joinTrainPart(MSVehicle *veh)
try joining the given vehicle to the rear of this one (to resolve joinTriggered)
MSLane * myLane
The lane the vehicle is on.
Definition MSVehicle.h:1909
bool onFurtherEdge(const MSEdge *edge) const
whether this vehicle has its back (and no its front) on the given edge
double processTraCISpeedControl(double vSafe, double vNext)
Check for speed advices from the traci client and adjust the speed vNext in the current (euler) / aft...
Manoeuvre myManoeuvre
Definition MSVehicle.h:1342
double getLateralOverlap() const
return the amount by which the vehicle extends laterally outside it's primary lane
double getAngle() const
Returns the vehicle's direction in radians.
Definition MSVehicle.h:735
bool handleCollisionStop(MSStop &stop, const double distToStop)
bool hasInfluencer() const
whether the vehicle is individually influenced (via TraCI or special parameters)
Definition MSVehicle.h:1706
MSDevice_Friction * myFrictionDevice
This vehicle's friction perception.
Definition MSVehicle.h:1898
double getPreviousSpeed() const
Returns the vehicle's speed before the previous time step.
Definition MSVehicle.h:498
MSVehicle()
invalidated default constructor
bool joinTrainPartFront(MSVehicle *veh)
try joining the given vehicle to the front of this one (to resolve joinTriggered)
void updateActionOffset(const SUMOTime oldActionStepLength, const SUMOTime newActionStepLength)
Process an updated action step length value (only affects the vehicle's action offset,...
double getBrakeGap(bool delayed=false) const
get distance for coming to a stop (used for rerouting checks)
std::pair< const MSVehicle *const, double > getLeader(double dist=0, bool considerFoes=true) const
Returns the leader of the vehicle looking for a fixed distance.
void executeFractionalMove(double dist)
move vehicle forward by the given distance during insertion
LaneChangeMode
modes for resolving conflicts between external control (traci) and vehicle control over lane changing...
Definition MSVehicle.h:1150
virtual void drawOutsideNetwork(bool)
register vehicle for drawing while outside the network
Definition MSVehicle.h:1857
void initDevices()
void adaptToOncomingLeader(const std::pair< const MSVehicle *, double > leaderInfo, DriveProcessItem *const lastLink, double &v, double &vLinkPass) const
void planMoveInternal(const SUMOTime t, MSLeaderInfo ahead, DriveItemVector &lfLinks, double &myStopDist, double &newStopSpeed, std::pair< double, const MSLink * > &myNextTurn) const
State myState
This Vehicles driving state (pos and speed)
Definition MSVehicle.h:1892
double getCenterOnEdge(const MSLane *lane=0) const
Get the vehicle's lateral position on the edge of the given lane (or its current edge if lane == 0)
void adaptToLeader(const std::pair< const MSVehicle *, double > leaderInfo, double seen, DriveProcessItem *const lastLink, double &v, double &vLinkPass) const
bool instantStopping() const
whether instant stopping is permitted
void switchOnSignal(int signal)
Switches the given signal on.
Definition MSVehicle.h:1169
static bool overlap(const MSVehicle *veh1, const MSVehicle *veh2)
Definition MSVehicle.h:767
int getLaneIndex() const
void updateParkingState()
update state while parking
DriveItemVector myLFLinkLanes
container for the planned speeds in the current step
Definition MSVehicle.h:2046
void updateDriveItems()
Check whether the drive items (myLFLinkLanes) are up to date, and update them if required.
SUMOTime myJunctionEntryTime
time at which the current junction was entered
Definition MSVehicle.h:1972
static MSVehicleTransfer * getInstance()
Returns the instance of this object.
void remove(MSVehicle *veh)
Remove a vehicle from this transfer object.
The car-following model and parameter.
double getLengthWithGap() const
Get vehicle's length including the minimum gap [m].
double getWidth() const
Get the width which vehicles of this class shall have when being drawn.
SUMOVehicleClass getVehicleClass() const
Get this vehicle type's vehicle class.
double getMaxSpeed() const
Get vehicle's (technical) maximum speed [m/s].
const std::string & getID() const
Returns the name of the vehicle type.
double getMinGap() const
Get the free space in front of vehicles of this class.
LaneChangeModel getLaneChangeModel() const
void setLength(const double &length)
Set a new value for this type's length.
SUMOTime getExitManoeuvreTime(const int angle) const
Accessor function for parameter equivalent returning exit time for a specific manoeuver angle.
const MSCFModel & getCarFollowModel() const
Returns the vehicle type's car following model definition (const version)
bool isVehicleSpecific() const
Returns whether this type belongs to a single vehicle only (was modified)
void setActionStepLength(const SUMOTime actionStepLength, bool resetActionOffset)
Set a new value for this type's action step length.
double getLength() const
Get vehicle's length [m].
SUMOVehicleShape getGuiShape() const
Get this vehicle type's shape.
SUMOTime getEntryManoeuvreTime(const int angle) const
Accessor function for parameter equivalent returning entry time for a specific manoeuver angle.
const SUMOVTypeParameter & getParameter() const
static std::string getIDSecure(const T *obj, const std::string &fallBack="NULL")
get an identifier for Named-like object which may be Null
Definition Named.h:66
const std::string & getID() const
Returns the id.
Definition Named.h:73
Static storage of an output device and its base (abstract) implementation.
OutputDevice & writeAttr(const ATTR_TYPE &attr, const T &val, const bool isNull=false, const bool escape=false)
writes a named attribute
bool closeTag(const std::string &comment="")
Closes the most recently opened tag and optionally adds a comment.
bool hasParameter(const std::string &key) const
Returns whether the parameter is set.
virtual const std::string getParameter(const std::string &key, const std::string defaultValue="") const
Returns the value for a given key.
A point in 2D or 3D with translation and scaling methods.
Definition Position.h:37
double slopeTo2D(const Position &other) const
returns the slope of the vector pointing from here to the other position (in radians between -M_PI an...
Definition Position.h:288
static const Position INVALID
used to indicate that a position is valid
Definition Position.h:323
double distanceTo2D(const Position &p2) const
returns the euclidean distance in the x-y-plane
Definition Position.h:273
void setz(double z)
set position z
Definition Position.h:77
double z() const
Returns the z-position.
Definition Position.h:62
double angleTo2D(const Position &other) const
returns the angle in the plane of the vector pointing from here to the other position (in radians bet...
Definition Position.h:283
A list of positions.
double length2D() const
Returns the length.
void append(const PositionVector &v, double sameThreshold=2.0)
double rotationAtOffset(double pos) const
Returns the rotation at the given length.
Position positionAtOffset(double pos, double lateralOffset=0) const
Returns the position at the given length.
void move2side(double amount, double maxExtension=100)
move position vector to side using certain amount
double slopeDegreeAtOffset(double pos) const
Returns the slope at the given length.
void extrapolate2D(const double val, const bool onlyFirst=false)
extrapolate position vector in two dimensions (Z is ignored)
void scaleRelative(double factor)
enlarges/shrinks the polygon by a factor based at the centroid
PositionVector reverse() const
reverse position vector
static double rand(SumoRNG *rng=nullptr)
Returns a random real number in [0, 1)
virtual bool compute(const E *from, const E *to, const V *const vehicle, SUMOTime msTime, std::vector< const E * > &into, bool silent=false)=0
Builds the route between the given edges using the minimum effort at the given time The definition of...
virtual double recomputeCosts(const std::vector< const E * > &edges, const V *const v, SUMOTime msTime, double *lengthp=nullptr) const
Encapsulated SAX-Attributes.
virtual std::string getString(int id, bool *isPresent=nullptr) const =0
Returns the string-value of the named (by its enum-value) attribute.
T getOpt(int attr, const char *objectid, bool &ok, T defaultValue=T(), bool report=true) const
Tries to read given attribute assuming it is an int.
T get(int attr, const char *objectid, bool &ok, bool report=true) const
Tries to read given attribute assuming it is an int.
virtual bool hasAttribute(int id) const =0
Returns the information whether the named (by its enum-value) attribute is within the current list.
double getFloat(int id) const
Returns the double-value of the named (by its enum-value) attribute.
Representation of a vehicle, person, or container.
virtual const MSVehicleType & getVehicleType() const =0
Returns the object's "vehicle" type.
virtual double getSpeed() const =0
Returns the object's current speed.
double locomotiveLength
the length of the locomotive
double speedFactorPremature
the possible speed reduction when a train is ahead of schedule
double getLCParam(const SumoXMLAttr attr, const double defaultValue) const
Returns the named value from the map, or the default if it is not contained there.
double getJMParam(const SumoXMLAttr attr, const double defaultValue) const
Returns the named value from the map, or the default if it is not contained there.
Representation of a vehicle.
Definition SUMOVehicle.h:63
Definition of vehicle stop (position and duration)
SUMOTime started
the time at which this stop was reached
ParkingType parking
whether the vehicle is removed from the net while stopping
SUMOTime extension
The maximum time extension for boarding / loading.
std::string split
the id of the vehicle (train portion) that splits of upon reaching this stop
double startPos
The stopping position start.
std::string line
the new line id of the trip within a cyclical public transport route
double posLat
the lateral offset when stopping
bool onDemand
whether the stop may be skipped
int parametersSet
Information for the output which parameter were set.
std::string join
the id of the vehicle (train portion) to which this vehicle shall be joined
SUMOTime until
The time at which the vehicle may continue its journey.
SUMOTime ended
the time at which this stop was ended
double endPos
The stopping position end.
SUMOTime waitUntil
The earliest pickup time for a taxi stop.
std::string tripId
id of the trip within a cyclical public transport route
bool collision
Whether this stop was triggered by a collision.
SUMOTime arrival
The (expected) time at which the vehicle reaches the stop.
SUMOTime duration
The stopping duration.
Structure representing possible vehicle parameter.
int departLane
(optional) The lane the vehicle shall depart from (index in edge)
ArrivalSpeedDefinition arrivalSpeedProcedure
Information how the vehicle's end speed shall be chosen.
double departSpeed
(optional) The initial speed of the vehicle
std::vector< std::string > via
List of the via-edges the vehicle must visit.
ArrivalLaneDefinition arrivalLaneProcedure
Information how the vehicle shall choose the lane to arrive on.
long long int parametersSet
Information for the router which parameter were set, TraCI may modify this (when changing color)
DepartLaneDefinition departLaneProcedure
Information how the vehicle shall choose the lane to depart from.
bool wasSet(long long int what) const
Returns whether the given parameter was set.
DepartSpeedDefinition departSpeedProcedure
Information how the vehicle's initial speed shall be chosen.
double arrivalPos
(optional) The position the vehicle shall arrive on
ArrivalPosDefinition arrivalPosProcedure
Information how the vehicle shall choose the arrival position.
double arrivalSpeed
(optional) The final speed of the vehicle (not used yet)
int arrivalEdge
(optional) The final edge within the route of the vehicle
DepartPosDefinition departPosProcedure
Information how the vehicle shall choose the departure position.
static SUMOTime processActionStepLength(double given)
Checks and converts given value for the action step length from seconds to miliseconds assuring it be...
std::vector< std::string > getVector()
return vector of strings
static OutputDevice & writeParams(OutputDevice &device, const Parameterised &params)
write the parameters of the given object as param tags
#define DEBUG_COND
Definition json.hpp:5639
NLOHMANN_BASIC_JSON_TPL_DECLARATION void swap(nlohmann::NLOHMANN_BASIC_JSON_TPL &j1, nlohmann::NLOHMANN_BASIC_JSON_TPL &j2) noexcept(//NOLINT(readability-inconsistent-declaration-parameter-name, cert-dcl58-cpp) is_nothrow_move_constructible< nlohmann::NLOHMANN_BASIC_JSON_TPL >::value &&//NOLINT(misc-redundant-expression, cppcoreguidelines-noexcept-swap, performance-noexcept-swap) is_nothrow_move_assignable< nlohmann::NLOHMANN_BASIC_JSON_TPL >::value)
exchanges the values of two JSON objects
Definition json.hpp:25297
#define M_PI
Definition odrSpiral.cpp:45
Drive process items represent bounds on the safe velocity corresponding to the upcoming links.
Definition MSVehicle.h:1985
void adaptStopSpeed(const double v)
Definition MSVehicle.h:2032
double getLeaveSpeed() const
Definition MSVehicle.h:2036
void adaptLeaveSpeed(const double v)
Definition MSVehicle.h:2024
static std::map< const MSVehicle *, GapControlState * > refVehMap
stores reference vehicles currently in use by a gapController
Definition MSVehicle.h:1415
static GapControlVehStateListener * myVehStateListener
Definition MSVehicle.h:1418
void activate(double tauOriginal, double tauTarget, double additionalGap, double duration, double changeRate, double maxDecel, const MSVehicle *refVeh)
Start gap control with given params.
static void cleanup()
Static cleanup (removes vehicle state listener)
void deactivate()
Stop gap control.
static void init()
Static initalization (adds vehicle state listener)
A structure representing the best lanes for continuing the current route starting at 'lane'.
Definition MSVehicle.h:861
double length
The overall length which may be driven when using this lane without a lane change.
Definition MSVehicle.h:865
bool allowsContinuation
Whether this lane allows to continue the drive.
Definition MSVehicle.h:875
double nextOccupation
As occupation, but without the first lane.
Definition MSVehicle.h:871
std::vector< MSLane * > bestContinuations
Definition MSVehicle.h:881
MSLane * lane
The described lane.
Definition MSVehicle.h:863
double currentLength
The length which may be driven on this lane.
Definition MSVehicle.h:867
int bestLaneOffset
The (signed) number of lanes to be crossed to get to the lane which allows to continue the drive.
Definition MSVehicle.h:873
double occupation
The overall vehicle sum on consecutive lanes which can be passed without a lane change.
Definition MSVehicle.h:869