LCOV - code coverage report
Current view: top level - src/microsim - MSVehicle.cpp (source / functions) Coverage Total Hit
Test: lcov.info Lines: 96.3 % 3284 3162
Test Date: 2025-12-06 15:35:27 Functions: 95.1 % 224 213

            Line data    Source code
       1              : /****************************************************************************/
       2              : // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
       3              : // Copyright (C) 2001-2025 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              : /****************************************************************************/
      14              : /// @file    MSVehicle.cpp
      15              : /// @author  Christian Roessel
      16              : /// @author  Jakob Erdmann
      17              : /// @author  Bjoern Hendriks
      18              : /// @author  Daniel Krajzewicz
      19              : /// @author  Thimor Bohn
      20              : /// @author  Friedemann Wesner
      21              : /// @author  Laura Bieker
      22              : /// @author  Clemens Honomichl
      23              : /// @author  Michael Behrisch
      24              : /// @author  Axel Wegener
      25              : /// @author  Christoph Sommer
      26              : /// @author  Leonhard Luecken
      27              : /// @author  Lara Codeca
      28              : /// @author  Mirko Barthauer
      29              : /// @date    Mon, 05 Mar 2001
      30              : ///
      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>
      42              : #include <utils/common/ToString.h>
      43              : #include <utils/common/FileHelpers.h>
      44              : #include <utils/router/DijkstraRouter.h>
      45              : #include <utils/common/MsgHandler.h>
      46              : #include <utils/common/RandHelper.h>
      47              : #include <utils/common/StringUtils.h>
      48              : #include <utils/common/StdDefs.h>
      49              : #include <utils/geom/GeomHelper.h>
      50              : #include <utils/iodevices/OutputDevice.h>
      51              : #include <utils/xml/SUMOSAXAttributes.h>
      52              : #include <utils/vehicle/SUMOVehicleParserHelper.h>
      53              : #include <microsim/lcmodels/MSAbstractLaneChangeModel.h>
      54              : #include <microsim/transportables/MSPerson.h>
      55              : #include <microsim/transportables/MSPModel.h>
      56              : #include <microsim/devices/MSDevice_Transportable.h>
      57              : #include <microsim/devices/MSDevice_DriverState.h>
      58              : #include <microsim/devices/MSDevice_Friction.h>
      59              : #include <microsim/devices/MSDevice_Taxi.h>
      60              : #include <microsim/devices/MSDevice_Vehroutes.h>
      61              : #include <microsim/devices/MSDevice_ElecHybrid.h>
      62              : #include <microsim/devices/MSDevice_GLOSA.h>
      63              : #include <microsim/output/MSStopOut.h>
      64              : #include <microsim/trigger/MSChargingStation.h>
      65              : #include <microsim/trigger/MSOverheadWire.h>
      66              : #include <microsim/traffic_lights/MSTrafficLightLogic.h>
      67              : #include <microsim/traffic_lights/MSRailSignalControl.h>
      68              : #include <microsim/lcmodels/MSAbstractLaneChangeModel.h>
      69              : #include <microsim/transportables/MSTransportableControl.h>
      70              : #include <microsim/devices/MSDevice_Transportable.h>
      71              : #include "MSEdgeControl.h"
      72              : #include "MSVehicleControl.h"
      73              : #include "MSInsertionControl.h"
      74              : #include "MSVehicleTransfer.h"
      75              : #include "MSGlobals.h"
      76              : #include "MSJunctionLogic.h"
      77              : #include "MSStop.h"
      78              : #include "MSStoppingPlace.h"
      79              : #include "MSParkingArea.h"
      80              : #include "MSMoveReminder.h"
      81              : #include "MSLane.h"
      82              : #include "MSJunction.h"
      83              : #include "MSEdge.h"
      84              : #include "MSVehicleType.h"
      85              : #include "MSNet.h"
      86              : #include "MSRoute.h"
      87              : #include "MSLeaderInfo.h"
      88              : #include "MSDriverState.h"
      89              : #include "MSVehicle.h"
      90              : 
      91              : 
      92              : //#define DEBUG_PLAN_MOVE
      93              : //#define DEBUG_PLAN_MOVE_LEADERINFO
      94              : //#define DEBUG_CHECKREWINDLINKLANES
      95              : //#define DEBUG_EXEC_MOVE
      96              : //#define DEBUG_FURTHER
      97              : //#define DEBUG_SETFURTHER
      98              : //#define DEBUG_TARGET_LANE
      99              : //#define DEBUG_STOPS
     100              : //#define DEBUG_BESTLANES
     101              : //#define DEBUG_IGNORE_RED
     102              : //#define DEBUG_ACTIONSTEPS
     103              : //#define DEBUG_NEXT_TURN
     104              : //#define DEBUG_TRACI
     105              : //#define DEBUG_REVERSE_BIDI
     106              : //#define DEBUG_EXTRAPOLATE_DEPARTPOS
     107              : //#define DEBUG_REMOTECONTROL
     108              : //#define DEBUG_MOVEREMINDERS
     109              : //#define DEBUG_COND (getID() == "ego")
     110              : //#define DEBUG_COND (true)
     111              : #define DEBUG_COND (isSelected())
     112              : //#define DEBUG_COND2(obj) (obj->getID() == "ego")
     113              : #define DEBUG_COND2(obj) (obj->isSelected())
     114              : 
     115              : //#define PARALLEL_STOPWATCH
     116              : 
     117              : 
     118              : #define STOPPING_PLACE_OFFSET 0.5
     119              : 
     120              : #define CRLL_LOOK_AHEAD 5
     121              : 
     122              : #define JUNCTION_BLOCKAGE_TIME 5 // s
     123              : 
     124              : // @todo Calibrate with real-world values / make configurable
     125              : #define DIST_TO_STOPLINE_EXPECT_PRIORITY 1.0
     126              : 
     127              : #define NUMERICAL_EPS_SPEED (0.1 * NUMERICAL_EPS * TS)
     128              : 
     129              : // ===========================================================================
     130              : // static value definitions
     131              : // ===========================================================================
     132              : std::vector<MSLane*> MSVehicle::myEmptyLaneVector;
     133              : 
     134              : 
     135              : // ===========================================================================
     136              : // method definitions
     137              : // ===========================================================================
     138              : /* -------------------------------------------------------------------------
     139              :  * methods of MSVehicle::State
     140              :  * ----------------------------------------------------------------------- */
     141            0 : MSVehicle::State::State(const State& state) {
     142            0 :     myPos = state.myPos;
     143            0 :     mySpeed = state.mySpeed;
     144            0 :     myPosLat = state.myPosLat;
     145            0 :     myBackPos = state.myBackPos;
     146            0 :     myPreviousSpeed = state.myPreviousSpeed;
     147            0 :     myLastCoveredDist = state.myLastCoveredDist;
     148            0 : }
     149              : 
     150              : 
     151              : MSVehicle::State&
     152      3121010 : MSVehicle::State::operator=(const State& state) {
     153      3121010 :     myPos   = state.myPos;
     154      3121010 :     mySpeed = state.mySpeed;
     155      3121010 :     myPosLat   = state.myPosLat;
     156      3121010 :     myBackPos = state.myBackPos;
     157      3121010 :     myPreviousSpeed = state.myPreviousSpeed;
     158      3121010 :     myLastCoveredDist = state.myLastCoveredDist;
     159      3121010 :     return *this;
     160              : }
     161              : 
     162              : 
     163              : bool
     164            0 : MSVehicle::State::operator!=(const State& state) {
     165            0 :     return (myPos    != state.myPos ||
     166            0 :             mySpeed  != state.mySpeed ||
     167            0 :             myPosLat != state.myPosLat ||
     168            0 :             myLastCoveredDist != state.myLastCoveredDist ||
     169            0 :             myPreviousSpeed != state.myPreviousSpeed ||
     170            0 :             myBackPos != state.myBackPos);
     171              : }
     172              : 
     173              : 
     174      7759869 : MSVehicle::State::State(double pos, double speed, double posLat, double backPos, double previousSpeed) :
     175      7759869 :     myPos(pos), mySpeed(speed), myPosLat(posLat), myBackPos(backPos), myPreviousSpeed(previousSpeed), myLastCoveredDist(SPEED2DIST(speed)) {}
     176              : 
     177              : 
     178              : 
     179              : /* -------------------------------------------------------------------------
     180              :  * methods of MSVehicle::WaitingTimeCollector
     181              :  * ----------------------------------------------------------------------- */
     182      4638859 : MSVehicle::WaitingTimeCollector::WaitingTimeCollector(SUMOTime memory) : myMemorySize(memory) {}
     183              : 
     184              : 
     185              : SUMOTime
     186      1428959 : MSVehicle::WaitingTimeCollector::cumulatedWaitingTime(SUMOTime memorySpan) const {
     187              :     assert(memorySpan <= myMemorySize);
     188      1428959 :     if (memorySpan == -1) {
     189            0 :         memorySpan = myMemorySize;
     190              :     }
     191              :     SUMOTime totalWaitingTime = 0;
     192      5954951 :     for (const auto& interval : myWaitingIntervals) {
     193      4525992 :         if (interval.second >= memorySpan) {
     194       655872 :             if (interval.first >= memorySpan) {
     195              :                 break;
     196              :             } else {
     197       655872 :                 totalWaitingTime += memorySpan - interval.first;
     198              :             }
     199              :         } else {
     200      3870120 :             totalWaitingTime += interval.second - interval.first;
     201              :         }
     202              :     }
     203      1428959 :     return totalWaitingTime;
     204              : }
     205              : 
     206              : 
     207              : void
     208    675941764 : MSVehicle::WaitingTimeCollector::passTime(SUMOTime dt, bool waiting) {
     209              :     auto i = myWaitingIntervals.begin();
     210              :     const auto end = myWaitingIntervals.end();
     211    675941764 :     const bool startNewInterval = i == end || (i->first != 0);
     212   1095451720 :     while (i != end) {
     213    421715455 :         i->first += dt;
     214    421715455 :         if (i->first >= myMemorySize) {
     215              :             break;
     216              :         }
     217    419509956 :         i->second += dt;
     218              :         i++;
     219              :     }
     220              : 
     221              :     // remove intervals beyond memorySize
     222              :     auto d = std::distance(i, end);
     223    678147263 :     while (d > 0) {
     224      2205499 :         myWaitingIntervals.pop_back();
     225      2205499 :         d--;
     226              :     }
     227              : 
     228    675941764 :     if (!waiting) {
     229              :         return;
     230     83723271 :     } else if (!startNewInterval) {
     231     80286073 :         myWaitingIntervals.begin()->first = 0;
     232              :     } else {
     233      6874396 :         myWaitingIntervals.push_front(std::make_pair(0, dt));
     234              :     }
     235              :     return;
     236              : }
     237              : 
     238              : 
     239              : const std::string
     240         2479 : MSVehicle::WaitingTimeCollector::getState() const {
     241         2479 :     std::ostringstream state;
     242         2479 :     state << myMemorySize << " " << myWaitingIntervals.size();
     243         3402 :     for (const auto& interval : myWaitingIntervals) {
     244         1846 :         state << " " << interval.first << " " << interval.second;
     245              :     }
     246         2479 :     return state.str();
     247         2479 : }
     248              : 
     249              : 
     250              : void
     251         4160 : MSVehicle::WaitingTimeCollector::setState(const std::string& state) {
     252         4160 :     std::istringstream is(state);
     253              :     int numIntervals;
     254              :     SUMOTime begin, end;
     255         4160 :     is >> myMemorySize >> numIntervals;
     256         6918 :     while (numIntervals-- > 0) {
     257              :         is >> begin >> end;
     258         2758 :         myWaitingIntervals.emplace_back(begin, end);
     259              :     }
     260         4160 : }
     261              : 
     262              : 
     263              : /* -------------------------------------------------------------------------
     264              :  * methods of MSVehicle::Influencer::GapControlState
     265              :  * ----------------------------------------------------------------------- */
     266              : void
     267           32 : MSVehicle::Influencer::GapControlVehStateListener::vehicleStateChanged(const SUMOVehicle* const vehicle, MSNet::VehicleState to, const std::string& /*info*/) {
     268              : //    std::cout << "GapControlVehStateListener::vehicleStateChanged() vehicle=" << vehicle->getID() << ", to=" << to << std::endl;
     269           32 :     switch (to) {
     270            5 :         case MSNet::VehicleState::STARTING_TELEPORT:
     271              :         case MSNet::VehicleState::ARRIVED:
     272              :         case MSNet::VehicleState::STARTING_PARKING: {
     273              :             // Vehicle left road
     274              : //         Look up reference vehicle in refVehMap and in case deactivate corresponding gap control
     275            5 :             const MSVehicle* msVeh = static_cast<const MSVehicle*>(vehicle);
     276              : //        std::cout << "GapControlVehStateListener::vehicleStateChanged() vehicle=" << vehicle->getID() << " left the road." << std::endl;
     277            5 :             if (GapControlState::refVehMap.find(msVeh) != end(GapControlState::refVehMap)) {
     278              : //            std::cout << "GapControlVehStateListener::deactivating ref vehicle=" << vehicle->getID() << std::endl;
     279            5 :                 GapControlState::refVehMap[msVeh]->deactivate();
     280              :             }
     281              :         }
     282            5 :         break;
     283           32 :         default:
     284              :         {};
     285              :             // do nothing, vehicle still on road
     286              :     }
     287           32 : }
     288              : 
     289              : std::map<const MSVehicle*, MSVehicle::Influencer::GapControlState*>
     290              : MSVehicle::Influencer::GapControlState::refVehMap;
     291              : 
     292              : MSVehicle::Influencer::GapControlVehStateListener* MSVehicle::Influencer::GapControlState::myVehStateListener(nullptr);
     293              : 
     294           59 : MSVehicle::Influencer::GapControlState::GapControlState() :
     295           59 :     tauOriginal(-1), tauCurrent(-1), tauTarget(-1), addGapCurrent(-1), addGapTarget(-1),
     296           59 :     remainingDuration(-1), changeRate(-1), maxDecel(-1), referenceVeh(nullptr), active(false), gapAttained(false), prevLeader(nullptr),
     297           59 :     lastUpdate(-1), timeHeadwayIncrement(0.0), spaceHeadwayIncrement(0.0) {}
     298              : 
     299              : 
     300           59 : MSVehicle::Influencer::GapControlState::~GapControlState() {
     301           59 :     deactivate();
     302           59 : }
     303              : 
     304              : void
     305           59 : MSVehicle::Influencer::GapControlState::init() {
     306           59 :     if (MSNet::hasInstance()) {
     307           59 :         if (myVehStateListener == nullptr) {
     308              :             //std::cout << "GapControlState::init()" << std::endl;
     309           59 :             myVehStateListener = new GapControlVehStateListener();
     310           59 :             MSNet::getInstance()->addVehicleStateListener(myVehStateListener);
     311              :         }
     312              :     } else {
     313            0 :         WRITE_ERROR("MSVehicle::Influencer::GapControlState::init(): No MSNet instance found!")
     314              :     }
     315           59 : }
     316              : 
     317              : void
     318        32760 : MSVehicle::Influencer::GapControlState::cleanup() {
     319        32760 :     if (myVehStateListener != nullptr) {
     320           59 :         MSNet::getInstance()->removeVehicleStateListener(myVehStateListener);
     321           59 :         delete myVehStateListener;
     322           59 :         myVehStateListener = nullptr;
     323              :     }
     324        32760 : }
     325              : 
     326              : void
     327           59 : MSVehicle::Influencer::GapControlState::activate(double tauOrig, double tauNew, double additionalGap, double dur, double rate, double decel, const MSVehicle* refVeh) {
     328           59 :     if (MSGlobals::gUseMesoSim) {
     329            0 :         WRITE_ERROR(TL("No gap control available for meso."))
     330              :     } else {
     331              :         // always deactivate control before activating (triggers clean-up of refVehMap)
     332              : //        std::cout << "activate gap control with refVeh=" << (refVeh==nullptr? "NULL" : refVeh->getID()) << std::endl;
     333           59 :         tauOriginal = tauOrig;
     334           59 :         tauCurrent = tauOrig;
     335           59 :         tauTarget = tauNew;
     336           59 :         addGapCurrent = 0.0;
     337           59 :         addGapTarget = additionalGap;
     338           59 :         remainingDuration = dur;
     339           59 :         changeRate = rate;
     340           59 :         maxDecel = decel;
     341           59 :         referenceVeh = refVeh;
     342           59 :         active = true;
     343           59 :         gapAttained = false;
     344           59 :         prevLeader = nullptr;
     345           59 :         lastUpdate = SIMSTEP - DELTA_T;
     346           59 :         timeHeadwayIncrement = changeRate * TS * (tauTarget - tauOriginal);
     347           59 :         spaceHeadwayIncrement = changeRate * TS * addGapTarget;
     348              : 
     349           59 :         if (referenceVeh != nullptr) {
     350              :             // Add refVeh to refVehMap
     351           13 :             GapControlState::refVehMap[referenceVeh] = this;
     352              :         }
     353              :     }
     354           59 : }
     355              : 
     356              : void
     357          118 : MSVehicle::Influencer::GapControlState::deactivate() {
     358          118 :     active = false;
     359          118 :     if (referenceVeh != nullptr) {
     360              :         // Remove corresponding refVehMapEntry if appropriate
     361           13 :         GapControlState::refVehMap.erase(referenceVeh);
     362           13 :         referenceVeh = nullptr;
     363              :     }
     364          118 : }
     365              : 
     366              : 
     367              : /* -------------------------------------------------------------------------
     368              :  * methods of MSVehicle::Influencer
     369              :  * ----------------------------------------------------------------------- */
     370         3562 : MSVehicle::Influencer::Influencer() :
     371              :     myGapControlState(nullptr),
     372         3562 :     myOriginalSpeed(-1),
     373         3562 :     myLatDist(0),
     374         3562 :     mySpeedAdaptationStarted(true),
     375         3562 :     myConsiderSafeVelocity(true),
     376         3562 :     myConsiderSpeedLimit(true),
     377         3562 :     myConsiderMaxAcceleration(true),
     378         3562 :     myConsiderMaxDeceleration(true),
     379         3562 :     myRespectJunctionPriority(true),
     380         3562 :     myEmergencyBrakeRedLight(true),
     381         3562 :     myRespectJunctionLeaderPriority(true),
     382         3562 :     myLastRemoteAccess(-TIME2STEPS(20)),
     383         3562 :     myStrategicLC(LC_NOCONFLICT),
     384         3562 :     myCooperativeLC(LC_NOCONFLICT),
     385         3562 :     mySpeedGainLC(LC_NOCONFLICT),
     386         3562 :     myRightDriveLC(LC_NOCONFLICT),
     387         3562 :     mySublaneLC(LC_NOCONFLICT),
     388         3562 :     myTraciLaneChangePriority(LCP_URGENT),
     389         3562 :     myTraCISignals(-1)
     390         3562 : {}
     391              : 
     392              : 
     393        10686 : MSVehicle::Influencer::~Influencer() {}
     394              : 
     395              : void
     396           59 : MSVehicle::Influencer::init() {
     397           59 :     GapControlState::init();
     398           59 : }
     399              : 
     400              : void
     401        32760 : MSVehicle::Influencer::cleanup() {
     402        32760 :     GapControlState::cleanup();
     403        32760 : }
     404              : 
     405              : void
     406        42893 : MSVehicle::Influencer::setSpeedTimeLine(const std::vector<std::pair<SUMOTime, double> >& speedTimeLine) {
     407        42893 :     mySpeedAdaptationStarted = true;
     408        42893 :     mySpeedTimeLine = speedTimeLine;
     409        42893 : }
     410              : 
     411              : void
     412           59 : MSVehicle::Influencer::activateGapController(double originalTau, double newTimeHeadway, double newSpaceHeadway, double duration, double changeRate, double maxDecel, MSVehicle* refVeh) {
     413           59 :     if (myGapControlState == nullptr) {
     414           59 :         myGapControlState = std::make_shared<GapControlState>();
     415           59 :         init(); // only does things on first call
     416              :     }
     417           59 :     myGapControlState->activate(originalTau, newTimeHeadway, newSpaceHeadway, duration, changeRate, maxDecel, refVeh);
     418           59 : }
     419              : 
     420              : void
     421           10 : MSVehicle::Influencer::deactivateGapController() {
     422           10 :     if (myGapControlState != nullptr && myGapControlState->active) {
     423           10 :         myGapControlState->deactivate();
     424              :     }
     425           10 : }
     426              : 
     427              : void
     428         7979 : MSVehicle::Influencer::setLaneTimeLine(const std::vector<std::pair<SUMOTime, int> >& laneTimeLine) {
     429         7979 :     myLaneTimeLine = laneTimeLine;
     430         7979 : }
     431              : 
     432              : 
     433              : void
     434         9101 : MSVehicle::Influencer::adaptLaneTimeLine(int indexShift) {
     435        19331 :     for (auto& item : myLaneTimeLine) {
     436        10230 :         item.second += indexShift;
     437              :     }
     438         9101 : }
     439              : 
     440              : 
     441              : void
     442         1487 : MSVehicle::Influencer::setSublaneChange(double latDist) {
     443         1487 :     myLatDist = latDist;
     444         1487 : }
     445              : 
     446              : int
     447           74 : MSVehicle::Influencer::getSpeedMode() const {
     448           74 :     return (1 * myConsiderSafeVelocity +
     449           74 :             2 * myConsiderMaxAcceleration +
     450           74 :             4 * myConsiderMaxDeceleration +
     451           74 :             8 * myRespectJunctionPriority +
     452           74 :             16 * myEmergencyBrakeRedLight +
     453           74 :             32 * !myRespectJunctionLeaderPriority + // inverted!
     454           74 :             64 * !myConsiderSpeedLimit // inverted!
     455           74 :            );
     456              : }
     457              : 
     458              : 
     459              : int
     460         1476 : MSVehicle::Influencer::getLaneChangeMode() const {
     461         1476 :     return (1 * myStrategicLC +
     462         1476 :             4 * myCooperativeLC +
     463         1476 :             16 * mySpeedGainLC +
     464         1476 :             64 * myRightDriveLC +
     465         1476 :             256 * myTraciLaneChangePriority +
     466         1476 :             1024 * mySublaneLC);
     467              : }
     468              : 
     469              : SUMOTime
     470           71 : MSVehicle::Influencer::getLaneTimeLineDuration() {
     471              :     SUMOTime duration = -1;
     472          213 :     for (std::vector<std::pair<SUMOTime, int>>::iterator i = myLaneTimeLine.begin(); i != myLaneTimeLine.end(); ++i) {
     473          142 :         if (duration < 0) {
     474           71 :             duration = i->first;
     475              :         } else {
     476           71 :             duration -=  i->first;
     477              :         }
     478              :     }
     479           71 :     return -duration;
     480              : }
     481              : 
     482              : SUMOTime
     483            0 : MSVehicle::Influencer::getLaneTimeLineEnd() {
     484            0 :     if (!myLaneTimeLine.empty()) {
     485            0 :         return myLaneTimeLine.back().first;
     486              :     } else {
     487              :         return -1;
     488              :     }
     489              : }
     490              : 
     491              : 
     492              : double
     493       997534 : MSVehicle::Influencer::influenceSpeed(SUMOTime currentTime, double speed, double vSafe, double vMin, double vMax) {
     494              :     // remove leading commands which are no longer valid
     495       998870 :     while (mySpeedTimeLine.size() == 1 || (mySpeedTimeLine.size() > 1 && currentTime > mySpeedTimeLine[1].first)) {
     496              :         mySpeedTimeLine.erase(mySpeedTimeLine.begin());
     497              :     }
     498              : 
     499       997534 :     if (!(mySpeedTimeLine.size() < 2 || currentTime < mySpeedTimeLine[0].first)) {
     500              :         // Speed advice is active -> compute new speed according to speedTimeLine
     501        54435 :         if (!mySpeedAdaptationStarted) {
     502            0 :             mySpeedTimeLine[0].second = speed;
     503            0 :             mySpeedAdaptationStarted = true;
     504              :         }
     505        54435 :         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)
     506       108518 :         const double td = MIN2(1.0, STEPS2TIME(currentTime - mySpeedTimeLine[0].first) / MAX2(TS, STEPS2TIME(mySpeedTimeLine[1].first - mySpeedTimeLine[0].first)));
     507              : 
     508        54435 :         speed = mySpeedTimeLine[0].second - (mySpeedTimeLine[0].second - mySpeedTimeLine[1].second) * td;
     509        54435 :         if (myConsiderSafeVelocity) {
     510              :             speed = MIN2(speed, vSafe);
     511              :         }
     512        54435 :         if (myConsiderMaxAcceleration) {
     513              :             speed = MIN2(speed, vMax);
     514              :         }
     515        54435 :         if (myConsiderMaxDeceleration) {
     516              :             speed = MAX2(speed, vMin);
     517              :         }
     518              :     }
     519       997534 :     return speed;
     520              : }
     521              : 
     522              : double
     523       495467 : MSVehicle::Influencer::gapControlSpeed(SUMOTime currentTime, const SUMOVehicle* veh, double speed, double vSafe, double vMin, double vMax) {
     524              : #ifdef DEBUG_TRACI
     525              :     if DEBUG_COND2(veh) {
     526              :         std::cout << currentTime << " Influencer::gapControlSpeed(): speed=" << speed
     527              :                   << ", vSafe=" << vSafe
     528              :                   << ", vMin=" << vMin
     529              :                   << ", vMax=" << vMax
     530              :                   << std::endl;
     531              :     }
     532              : #endif
     533              :     double gapControlSpeed = speed;
     534       495467 :     if (myGapControlState != nullptr && myGapControlState->active) {
     535              :         // Determine leader and the speed that would be chosen by the gap controller
     536         7778 :         const double currentSpeed = veh->getSpeed();
     537         7778 :         const MSVehicle* msVeh = dynamic_cast<const MSVehicle*>(veh);
     538              :         assert(msVeh != nullptr);
     539         7778 :         const double desiredTargetTimeSpacing = myGapControlState->tauTarget * currentSpeed;
     540              :         std::pair<const MSVehicle*, double> leaderInfo;
     541         7778 :         if (myGapControlState->referenceVeh == nullptr) {
     542              :             // No reference vehicle specified -> use current leader as reference
     543         7340 :             const double brakeGap = msVeh->getBrakeGap(true);
     544        14680 :             leaderInfo = msVeh->getLeader(MAX2(desiredTargetTimeSpacing, myGapControlState->addGapCurrent)  + MAX2(brakeGap, 20.0));
     545              : #ifdef DEBUG_TRACI
     546              :             if DEBUG_COND2(veh) {
     547              :                 std::cout <<  "  ---   no refVeh; myGapControlState->addGapCurrent: " << myGapControlState->addGapCurrent << ", brakeGap: " << brakeGap << " in simstep: " << SIMSTEP << std::endl;
     548              :             }
     549              : #endif
     550              :         } else {
     551              :             // Control gap wrt reference vehicle
     552              :             const MSVehicle* leader = myGapControlState->referenceVeh;
     553          438 :             double dist = msVeh->getDistanceToPosition(leader->getPositionOnLane(), leader->getLane()) - leader->getLength();
     554          438 :             if (dist > 100000) {
     555              :                 // Reference vehicle was not found downstream the ego's route
     556              :                 // Maybe, it is behind the ego vehicle
     557           42 :                 dist = - leader->getDistanceToPosition(msVeh->getPositionOnLane(), msVeh->getLane()) - leader->getLength();
     558              : #ifdef DEBUG_TRACI
     559              :                 if DEBUG_COND2(veh) {
     560              :                     if (dist < -100000) {
     561              :                         // also the ego vehicle is not ahead of the reference vehicle -> no CF-relation
     562              :                         std::cout <<  " Ego and reference vehicle are not in CF relation..." << std::endl;
     563              :                     } else {
     564              :                         std::cout <<  " Reference vehicle is behind ego..." << std::endl;
     565              :                     }
     566              :                 }
     567              : #endif
     568              :             }
     569          438 :             leaderInfo = std::make_pair(leader, dist - msVeh->getVehicleType().getMinGap());
     570              :         }
     571         7778 :         const double fakeDist = MAX2(0.0, leaderInfo.second - myGapControlState->addGapCurrent);
     572              : #ifdef DEBUG_TRACI
     573              :         if DEBUG_COND2(veh) {
     574              :             const double desiredCurrentSpacing = myGapControlState->tauCurrent * currentSpeed;
     575              :             std::cout <<  " Gap control active:"
     576              :                       << " currentSpeed=" << currentSpeed
     577              :                       << ", desiredTargetTimeSpacing=" << desiredTargetTimeSpacing
     578              :                       << ", desiredCurrentSpacing=" << desiredCurrentSpacing
     579              :                       << ", leader=" << (leaderInfo.first == nullptr ? "NULL" : leaderInfo.first->getID())
     580              :                       << ", dist=" << leaderInfo.second
     581              :                       << ", fakeDist=" << fakeDist
     582              :                       << ",\n tauOriginal=" << myGapControlState->tauOriginal
     583              :                       << ", tauTarget=" << myGapControlState->tauTarget
     584              :                       << ", tauCurrent=" << myGapControlState->tauCurrent
     585              :                       << std::endl;
     586              :         }
     587              : #endif
     588         7778 :         if (leaderInfo.first != nullptr) {
     589              :             if (myGapControlState->prevLeader != nullptr && myGapControlState->prevLeader != leaderInfo.first) {
     590              :                 // TODO: The leader changed. What to do?
     591              :             }
     592              :             // Remember leader
     593         7778 :             myGapControlState->prevLeader = leaderInfo.first;
     594              : 
     595              :             // Calculate desired following speed assuming the alternative headway time
     596         7778 :             MSCFModel* cfm = (MSCFModel*) & (msVeh->getVehicleType().getCarFollowModel());
     597         7778 :             const double origTau = cfm->getHeadwayTime();
     598         7778 :             cfm->setHeadwayTime(myGapControlState->tauCurrent);
     599         7778 :             gapControlSpeed = MIN2(gapControlSpeed,
     600         7778 :                                    cfm->followSpeed(msVeh, currentSpeed, fakeDist, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first));
     601         7778 :             cfm->setHeadwayTime(origTau);
     602              : #ifdef DEBUG_TRACI
     603              :             if DEBUG_COND2(veh) {
     604              :                 std::cout << " -> gapControlSpeed=" << gapControlSpeed;
     605              :                 if (myGapControlState->maxDecel > 0) {
     606              :                     std::cout << ", with maxDecel bound: " << MAX2(gapControlSpeed, currentSpeed - TS * myGapControlState->maxDecel);
     607              :                 }
     608              :                 std::cout << std::endl;
     609              :             }
     610              : #endif
     611         7778 :             if (myGapControlState->maxDecel > 0) {
     612         2568 :                 gapControlSpeed = MAX2(gapControlSpeed, currentSpeed - TS * myGapControlState->maxDecel);
     613              :             }
     614              :         }
     615              : 
     616              :         // Update gap controller
     617              :         // Check (1) if the gap control has established the desired gap,
     618              :         // and (2) if it has maintained active for the given duration afterwards
     619         7778 :         if (myGapControlState->lastUpdate < currentTime) {
     620              : #ifdef DEBUG_TRACI
     621              :             if DEBUG_COND2(veh) {
     622              :                 std::cout << " Updating GapControlState." << std::endl;
     623              :             }
     624              : #endif
     625         7778 :             if (myGapControlState->tauCurrent == myGapControlState->tauTarget && myGapControlState->addGapCurrent == myGapControlState->addGapTarget) {
     626         2992 :                 if (!myGapControlState->gapAttained) {
     627              :                     // Check if the desired gap was established (add the POSITION_EPS to avoid infinite asymptotic behavior without having established the gap)
     628         4180 :                     myGapControlState->gapAttained = leaderInfo.first == nullptr ||  leaderInfo.second > MAX2(desiredTargetTimeSpacing, myGapControlState->addGapTarget) - POSITION_EPS;
     629              : #ifdef DEBUG_TRACI
     630              :                     if DEBUG_COND2(veh) {
     631              :                         if (myGapControlState->gapAttained) {
     632              :                             std::cout << "   Target gap was established." << std::endl;
     633              :                         }
     634              :                     }
     635              : #endif
     636              :                 } else {
     637              :                     // Count down remaining time if desired gap was established
     638          924 :                     myGapControlState->remainingDuration -= TS;
     639              : #ifdef DEBUG_TRACI
     640              :                     if DEBUG_COND2(veh) {
     641              :                         std::cout << "   Gap control remaining duration: " << myGapControlState->remainingDuration << std::endl;
     642              :                     }
     643              : #endif
     644          924 :                     if (myGapControlState->remainingDuration <= 0) {
     645              : #ifdef DEBUG_TRACI
     646              :                         if DEBUG_COND2(veh) {
     647              :                             std::cout << "   Gap control duration expired, deactivating control." << std::endl;
     648              :                         }
     649              : #endif
     650              :                         // switch off gap control
     651           44 :                         myGapControlState->deactivate();
     652              :                     }
     653              :                 }
     654              :             } else {
     655              :                 // Adjust current headway values
     656         4786 :                 myGapControlState->tauCurrent = MIN2(myGapControlState->tauCurrent + myGapControlState->timeHeadwayIncrement, myGapControlState->tauTarget);
     657         5168 :                 myGapControlState->addGapCurrent = MIN2(myGapControlState->addGapCurrent + myGapControlState->spaceHeadwayIncrement, myGapControlState->addGapTarget);
     658              :             }
     659              :         }
     660         7778 :         if (myConsiderSafeVelocity) {
     661              :             gapControlSpeed = MIN2(gapControlSpeed, vSafe);
     662              :         }
     663         7778 :         if (myConsiderMaxAcceleration) {
     664              :             gapControlSpeed = MIN2(gapControlSpeed, vMax);
     665              :         }
     666         7778 :         if (myConsiderMaxDeceleration) {
     667              :             gapControlSpeed = MAX2(gapControlSpeed, vMin);
     668              :         }
     669              :         return MIN2(speed, gapControlSpeed);
     670              :     } else {
     671              :         return speed;
     672              :     }
     673              : }
     674              : 
     675              : double
     676         7086 : MSVehicle::Influencer::getOriginalSpeed() const {
     677         7086 :     return myOriginalSpeed;
     678              : }
     679              : 
     680              : void
     681       502067 : MSVehicle::Influencer::setOriginalSpeed(double speed) {
     682       502067 :     myOriginalSpeed = speed;
     683       502067 : }
     684              : 
     685              : 
     686              : int
     687      2831674 : MSVehicle::Influencer::influenceChangeDecision(const SUMOTime currentTime, const MSEdge& currentEdge, const int currentLaneIndex, int state) {
     688              :     // remove leading commands which are no longer valid
     689      2831976 :     while (myLaneTimeLine.size() == 1 || (myLaneTimeLine.size() > 1 && currentTime > myLaneTimeLine[1].first)) {
     690              :         myLaneTimeLine.erase(myLaneTimeLine.begin());
     691              :     }
     692              :     ChangeRequest changeRequest = REQUEST_NONE;
     693              :     // do nothing if the time line does not apply for the current time
     694      2831674 :     if (myLaneTimeLine.size() >= 2 && currentTime >= myLaneTimeLine[0].first) {
     695       177680 :         const int destinationLaneIndex = myLaneTimeLine[1].second;
     696       177680 :         if (destinationLaneIndex < (int)currentEdge.getLanes().size()) {
     697       177319 :             if (currentLaneIndex > destinationLaneIndex) {
     698              :                 changeRequest = REQUEST_RIGHT;
     699       176236 :             } else if (currentLaneIndex < destinationLaneIndex) {
     700              :                 changeRequest = REQUEST_LEFT;
     701              :             } else {
     702              :                 changeRequest = REQUEST_HOLD;
     703              :             }
     704          361 :         } else if (currentEdge.getLanes().back()->getOpposite() != nullptr) { // change to opposite direction driving
     705              :             changeRequest = REQUEST_LEFT;
     706          361 :             state = state | LCA_TRACI;
     707              :         }
     708              :     }
     709              :     // check whether the current reason shall be canceled / overridden
     710      2831674 :     if ((state & LCA_WANTS_LANECHANGE_OR_STAY) != 0) {
     711              :         // flags for the current reason
     712              :         LaneChangeMode mode = LC_NEVER;
     713      1599207 :         if ((state & LCA_TRACI) != 0 && myLatDist != 0) {
     714              :             // security checks
     715         2825 :             if ((myTraciLaneChangePriority == LCP_ALWAYS)
     716          670 :                     || (myTraciLaneChangePriority == LCP_NOOVERLAP && (state & LCA_OVERLAPPING) == 0)) {
     717         2685 :                 state &= ~(LCA_BLOCKED | LCA_OVERLAPPING);
     718              :             }
     719              :             // continue sublane change manoeuvre
     720         2825 :             return state;
     721      1596382 :         } else if ((state & LCA_STRATEGIC) != 0) {
     722       481789 :             mode = myStrategicLC;
     723      1114593 :         } else if ((state & LCA_COOPERATIVE) != 0) {
     724           54 :             mode = myCooperativeLC;
     725      1114539 :         } else if ((state & LCA_SPEEDGAIN) != 0) {
     726        42444 :             mode = mySpeedGainLC;
     727      1072095 :         } else if ((state & LCA_KEEPRIGHT) != 0) {
     728         6220 :             mode = myRightDriveLC;
     729      1065875 :         } else if ((state & LCA_SUBLANE) != 0) {
     730      1065873 :             mode = mySublaneLC;
     731            2 :         } else if ((state & LCA_TRACI) != 0) {
     732              :             mode = LC_NEVER;
     733              :         } else {
     734            0 :             WRITE_WARNINGF(TL("Lane change model did not provide a reason for changing (state=%, time=%\n"), toString(state), time2string(currentTime));
     735              :         }
     736      1596380 :         if (mode == LC_NEVER) {
     737              :             // cancel all lcModel requests
     738              :             state &= ~LCA_WANTS_LANECHANGE_OR_STAY;
     739        44321 :             state &= ~LCA_URGENT;
     740        44321 :             if (changeRequest == REQUEST_NONE) {
     741              :                 // also remove all reasons except TRACI
     742        43757 :                 state &= ~LCA_CHANGE_REASONS | LCA_TRACI;
     743              :             }
     744      1552061 :         } else if (mode == LC_NOCONFLICT && changeRequest != REQUEST_NONE) {
     745         6869 :             if (
     746         6869 :                 ((state & LCA_LEFT) != 0 && changeRequest != REQUEST_LEFT) ||
     747         6619 :                 ((state & LCA_RIGHT) != 0 && changeRequest != REQUEST_RIGHT) ||
     748         6098 :                 ((state & LCA_STAY) != 0 && changeRequest != REQUEST_HOLD)) {
     749              :                 // cancel conflicting lcModel request
     750              :                 state &= ~LCA_WANTS_LANECHANGE_OR_STAY;
     751          935 :                 state &= ~LCA_URGENT;
     752              :             }
     753      1545192 :         } else if (mode == LC_ALWAYS) {
     754              :             // ignore any TraCI requests
     755              :             return state;
     756              :         }
     757              :     }
     758              :     // apply traci requests
     759      2822425 :     if (changeRequest == REQUEST_NONE) {
     760      2651625 :         return state;
     761              :     } else {
     762       177214 :         state |= LCA_TRACI;
     763              :         // security checks
     764       177214 :         if ((myTraciLaneChangePriority == LCP_ALWAYS)
     765       174945 :                 || (myTraciLaneChangePriority == LCP_NOOVERLAP && (state & LCA_OVERLAPPING) == 0)) {
     766         2761 :             state &= ~(LCA_BLOCKED | LCA_OVERLAPPING);
     767              :         }
     768       177214 :         if (changeRequest != REQUEST_HOLD && myTraciLaneChangePriority != LCP_OPPORTUNISTIC) {
     769         2531 :             state |= LCA_URGENT;
     770              :         }
     771         2560 :         switch (changeRequest) {
     772              :             case REQUEST_HOLD:
     773       174654 :                 return state | LCA_STAY;
     774         1577 :             case REQUEST_LEFT:
     775         1577 :                 return state | LCA_LEFT;
     776          983 :             case REQUEST_RIGHT:
     777          983 :                 return state | LCA_RIGHT;
     778              :             default:
     779              :                 throw ProcessError(TL("should not happen"));
     780              :         }
     781              :     }
     782              : }
     783              : 
     784              : 
     785              : double
     786          442 : MSVehicle::Influencer::changeRequestRemainingSeconds(const SUMOTime currentTime) const {
     787              :     assert(myLaneTimeLine.size() >= 2);
     788              :     assert(currentTime >= myLaneTimeLine[0].first);
     789          442 :     return STEPS2TIME(myLaneTimeLine[1].first - currentTime);
     790              : }
     791              : 
     792              : 
     793              : void
     794         5066 : MSVehicle::Influencer::setSpeedMode(int speedMode) {
     795         5066 :     myConsiderSafeVelocity = ((speedMode & 1) != 0);
     796         5066 :     myConsiderMaxAcceleration = ((speedMode & 2) != 0);
     797         5066 :     myConsiderMaxDeceleration = ((speedMode & 4) != 0);
     798         5066 :     myRespectJunctionPriority = ((speedMode & 8) != 0);
     799         5066 :     myEmergencyBrakeRedLight = ((speedMode & 16) != 0);
     800         5066 :     myRespectJunctionLeaderPriority = ((speedMode & 32) == 0); // inverted!
     801         5066 :     myConsiderSpeedLimit = ((speedMode & 64) == 0); // inverted!
     802         5066 : }
     803              : 
     804              : 
     805              : void
     806        18715 : MSVehicle::Influencer::setLaneChangeMode(int value) {
     807        18715 :     myStrategicLC = (LaneChangeMode)(value & (1 + 2));
     808        18715 :     myCooperativeLC = (LaneChangeMode)((value & (4 + 8)) >> 2);
     809        18715 :     mySpeedGainLC = (LaneChangeMode)((value & (16 + 32)) >> 4);
     810        18715 :     myRightDriveLC = (LaneChangeMode)((value & (64 + 128)) >> 6);
     811        18715 :     myTraciLaneChangePriority = (TraciLaneChangePriority)((value & (256 + 512)) >> 8);
     812        18715 :     mySublaneLC = (LaneChangeMode)((value & (1024 + 2048)) >> 10);
     813        18715 : }
     814              : 
     815              : 
     816              : void
     817         7800 : MSVehicle::Influencer::setRemoteControlled(Position xyPos, MSLane* l, double pos, double posLat, double angle, int edgeOffset, const ConstMSEdgeVector& route, SUMOTime t) {
     818         7800 :     myRemoteXYPos = xyPos;
     819         7800 :     myRemoteLane = l;
     820         7800 :     myRemotePos = pos;
     821         7800 :     myRemotePosLat = posLat;
     822         7800 :     myRemoteAngle = angle;
     823         7800 :     myRemoteEdgeOffset = edgeOffset;
     824         7800 :     myRemoteRoute = route;
     825         7800 :     myLastRemoteAccess = t;
     826         7800 : }
     827              : 
     828              : 
     829              : bool
     830      1027951 : MSVehicle::Influencer::isRemoteControlled() const {
     831      1027951 :     return myLastRemoteAccess == MSNet::getInstance()->getCurrentTimeStep();
     832              : }
     833              : 
     834              : 
     835              : bool
     836       489053 : MSVehicle::Influencer::isRemoteAffected(SUMOTime t) const {
     837       489053 :     return myLastRemoteAccess >= t - TIME2STEPS(10);
     838              : }
     839              : 
     840              : 
     841              : void
     842       495467 : MSVehicle::Influencer::updateRemoteControlRoute(MSVehicle* v) {
     843       495467 :     if (myRemoteRoute.size() != 0 && myRemoteRoute != v->getRoute().getEdges()) {
     844              :         // only replace route at this time if the vehicle is moving with the flow
     845           62 :         const bool isForward = v->getLane() != 0 && &v->getLane()->getEdge() == myRemoteRoute[0];
     846              : #ifdef DEBUG_REMOTECONTROL
     847              :         std::cout << SIMSTEP << " updateRemoteControlRoute veh=" << v->getID() << " old=" << toString(v->getRoute().getEdges()) << " new=" << toString(myRemoteRoute) << " fwd=" << isForward << "\n";
     848              : #endif
     849              :         if (isForward) {
     850           10 :             v->replaceRouteEdges(myRemoteRoute, -1, 0, "traci:moveToXY", true);
     851           10 :             v->updateBestLanes();
     852              :         }
     853              :     }
     854       495467 : }
     855              : 
     856              : 
     857              : void
     858         7775 : MSVehicle::Influencer::postProcessRemoteControl(MSVehicle* v) {
     859         7775 :     const bool wasOnRoad = v->isOnRoad();
     860         7775 :     const bool withinLane = myRemoteLane != nullptr && fabs(myRemotePosLat) < 0.5 * (myRemoteLane->getWidth() + v->getVehicleType().getWidth());
     861         7775 :     const bool keepLane = wasOnRoad && v->getLane() == myRemoteLane;
     862         7775 :     if (v->isOnRoad() && !(keepLane && withinLane)) {
     863          150 :         if (myRemoteLane != nullptr && &v->getLane()->getEdge() == &myRemoteLane->getEdge()) {
     864              :             // correct odometer which gets incremented via onRemovalFromNet->leaveLane
     865           71 :             v->myOdometer -= v->getLane()->getLength();
     866              :         }
     867          150 :         v->onRemovalFromNet(MSMoveReminder::NOTIFICATION_TELEPORT);
     868          150 :         v->getMutableLane()->removeVehicle(v, MSMoveReminder::NOTIFICATION_TELEPORT, false);
     869              :     }
     870         7775 :     if (myRemoteRoute.size() != 0 && myRemoteRoute != v->getRoute().getEdges()) {
     871              :         // needed for the insertion step
     872              : #ifdef DEBUG_REMOTECONTROL
     873              :         std::cout << SIMSTEP << " postProcessRemoteControl veh=" << v->getID()
     874              :                   << "\n  oldLane=" << Named::getIDSecure(v->getLane())
     875              :                   << " oldRoute=" << toString(v->getRoute().getEdges())
     876              :                   << "\n  newLane=" << Named::getIDSecure(myRemoteLane)
     877              :                   << " newRoute=" << toString(myRemoteRoute)
     878              :                   << " newRouteEdge=" << myRemoteRoute[myRemoteEdgeOffset]->getID()
     879              :                   << "\n";
     880              : #endif
     881              :         // clear any prior stops because they cannot apply to the new route
     882           67 :         const_cast<SUMOVehicleParameter&>(v->getParameter()).stops.clear();
     883          134 :         v->replaceRouteEdges(myRemoteRoute, -1, 0, "traci:moveToXY", true);
     884              :         myRemoteRoute.clear();
     885              :     }
     886         7775 :     v->myCurrEdge = v->getRoute().begin() + myRemoteEdgeOffset;
     887         7775 :     if (myRemoteLane != nullptr && myRemotePos > myRemoteLane->getLength()) {
     888            0 :         myRemotePos = myRemoteLane->getLength();
     889              :     }
     890         7775 :     if (myRemoteLane != nullptr && withinLane) {
     891         7593 :         if (keepLane) {
     892              :             // TODO this handles only the case when the new vehicle is completely on the edge
     893         7415 :             const bool needFurtherUpdate = v->myState.myPos < v->getVehicleType().getLength() && myRemotePos >= v->getVehicleType().getLength();
     894         7415 :             v->myState.myPos = myRemotePos;
     895         7415 :             v->myState.myPosLat = myRemotePosLat;
     896         7415 :             if (needFurtherUpdate) {
     897            5 :                 v->myState.myBackPos = v->updateFurtherLanes(v->myFurtherLanes, v->myFurtherLanesPosLat, std::vector<MSLane*>());
     898              :             }
     899              :         } else {
     900          178 :             MSMoveReminder::Notification notify = v->getDeparture() == NOT_YET_DEPARTED
     901          178 :                                                   ? MSMoveReminder::NOTIFICATION_DEPARTED
     902              :                                                   : MSMoveReminder::NOTIFICATION_TELEPORT_ARRIVED;
     903          178 :             if (!v->isOnRoad()) {
     904          178 :                 MSVehicleTransfer::getInstance()->remove(v);  // TODO may need optimization, this is linear in the number of vehicles in transfer
     905              :             }
     906          178 :             myRemoteLane->forceVehicleInsertion(v, myRemotePos, notify, myRemotePosLat);
     907          178 :             v->updateBestLanes();
     908              :         }
     909         7593 :         if (!wasOnRoad) {
     910           65 :             v->drawOutsideNetwork(false);
     911              :         }
     912              :         //std::cout << "on road network p=" << myRemoteXYPos << " a=" << myRemoteAngle << " l=" << Named::getIDSecure(myRemoteLane) << " pos=" << myRemotePos << " posLat=" << myRemotePosLat << "\n";
     913         7593 :         myRemoteLane->requireCollisionCheck();
     914              :     } else {
     915          182 :         if (v->getDeparture() == NOT_YET_DEPARTED) {
     916            5 :             v->onDepart();
     917              :         }
     918          182 :         v->drawOutsideNetwork(true);
     919              :         // see updateState
     920          182 :         double vNext = v->processTraCISpeedControl(
     921          182 :                            v->getMaxSpeed(), v->getSpeed());
     922          182 :         v->setBrakingSignals(vNext);
     923          182 :         v->myState.myPreviousSpeed = v->getSpeed();
     924          182 :         v->myAcceleration = SPEED2ACCEL(vNext - v->getSpeed());
     925          182 :         v->myState.mySpeed = vNext;
     926          182 :         v->updateWaitingTime(vNext);
     927              :         //std::cout << "outside network p=" << myRemoteXYPos << " a=" << myRemoteAngle << " l=" << Named::getIDSecure(myRemoteLane) << "\n";
     928              :     }
     929              :     // ensure that the position is correct (i.e. when the lanePosition is ambiguous at corners)
     930         7775 :     v->setRemoteState(myRemoteXYPos);
     931         7775 :     v->setAngle(GeomHelper::fromNaviDegree(myRemoteAngle));
     932         7775 : }
     933              : 
     934              : 
     935              : double
     936         7752 : MSVehicle::Influencer::implicitSpeedRemote(const MSVehicle* veh, double oldSpeed) {
     937         7752 :     if (veh->getPosition() == Position::INVALID) {
     938           10 :         return oldSpeed;
     939              :     }
     940         7742 :     double dist = veh->getPosition().distanceTo2D(myRemoteXYPos);
     941         7742 :     if (myRemoteLane != nullptr) {
     942              :         // if the vehicles is frequently placed on a new edge, the route may
     943              :         // consist only of a single edge. In this case the new edge may not be
     944              :         // on the route so distAlongRoute will be double::max.
     945              :         // In this case we still want a sensible speed value
     946         7600 :         const double distAlongRoute = veh->getDistanceToPosition(myRemotePos, myRemoteLane);
     947         7600 :         if (distAlongRoute != std::numeric_limits<double>::max()) {
     948              :             dist = distAlongRoute;
     949              :         }
     950              :     }
     951              :     //std::cout << SIMTIME << " veh=" << veh->getID() << " oldPos=" << veh->getPosition() << " traciPos=" << myRemoteXYPos << " dist=" << dist << "\n";
     952         7742 :     const double minSpeed = myConsiderMaxDeceleration ?
     953         5034 :                             veh->getCarFollowModel().minNextSpeedEmergency(oldSpeed, veh) : 0;
     954         7742 :     const double maxSpeed = (myRemoteLane != nullptr
     955         7742 :                              ? myRemoteLane->getVehicleMaxSpeed(veh)
     956          142 :                              : (veh->getLane() != nullptr
     957          142 :                                 ? veh->getLane()->getVehicleMaxSpeed(veh)
     958            5 :                                 : veh->getMaxSpeed()));
     959         7742 :     return MIN2(maxSpeed, MAX2(minSpeed, DIST2SPEED(dist)));
     960              : }
     961              : 
     962              : 
     963              : double
     964         7580 : MSVehicle::Influencer::implicitDeltaPosRemote(const MSVehicle* veh) {
     965              :     double dist = 0;
     966         7580 :     if (myRemoteLane == nullptr) {
     967            6 :         dist = veh->getPosition().distanceTo2D(myRemoteXYPos);
     968              :     } else {
     969              :         // if the vehicles is frequently placed on a new edge, the route may
     970              :         // consist only of a single edge. In this case the new edge may not be
     971              :         // on the route so getDistanceToPosition will return double::max.
     972              :         // In this case we would rather not move the vehicle in executeMove
     973              :         // (updateState) as it would result in emergency braking
     974         7574 :         dist = veh->getDistanceToPosition(myRemotePos, myRemoteLane);
     975              :     }
     976         7580 :     if (dist == std::numeric_limits<double>::max()) {
     977              :         return 0;
     978              :     } else {
     979         7339 :         if (DIST2SPEED(dist) > veh->getMaxSpeed() * 1.1) {
     980           48 :             WRITE_WARNINGF(TL("Vehicle '%' moved by TraCI from % to % (dist %) with implied speed of % (exceeding maximum speed %). time=%."),
     981              :                            veh->getID(), veh->getPosition(), myRemoteXYPos, dist, DIST2SPEED(dist), veh->getMaxSpeed(), time2string(SIMSTEP));
     982              :             // some sanity check here
     983           16 :             dist = MIN2(dist, SPEED2DIST(veh->getMaxSpeed() * 2));
     984              :         }
     985         7339 :         return dist;
     986              :     }
     987              : }
     988              : 
     989              : 
     990              : /* -------------------------------------------------------------------------
     991              :  * MSVehicle-methods
     992              :  * ----------------------------------------------------------------------- */
     993      4638859 : MSVehicle::MSVehicle(SUMOVehicleParameter* pars, ConstMSRoutePtr route,
     994      4638859 :                      MSVehicleType* type, const double speedFactor) :
     995              :     MSBaseVehicle(pars, route, type, speedFactor),
     996      4638859 :     myWaitingTime(0),
     997      4638859 :     myWaitingTimeCollector(),
     998      4638859 :     myTimeLoss(0),
     999      4638859 :     myState(0, 0, 0, 0, 0),
    1000      4638859 :     myDriverState(nullptr),
    1001      4638859 :     myActionStep(true),
    1002      4638859 :     myLastActionTime(0),
    1003      4638859 :     myLane(nullptr),
    1004      4638859 :     myLaneChangeModel(nullptr),
    1005      4638859 :     myLastBestLanesEdge(nullptr),
    1006      4638859 :     myLastBestLanesInternalLane(nullptr),
    1007      4638859 :     myAcceleration(0),
    1008              :     myNextTurn(0., nullptr),
    1009      4638859 :     mySignals(0),
    1010      4638859 :     myAmOnNet(false),
    1011      4638859 :     myAmIdling(false),
    1012      4638859 :     myHaveToWaitOnNextLink(false),
    1013      4638859 :     myAngle(0),
    1014      4638859 :     myStopDist(std::numeric_limits<double>::max()),
    1015      4638859 :     myCollisionImmunity(-1),
    1016      4638859 :     myCachedPosition(Position::INVALID),
    1017      4638859 :     myJunctionEntryTime(SUMOTime_MAX),
    1018      4638859 :     myJunctionEntryTimeNeverYield(SUMOTime_MAX),
    1019      4638859 :     myJunctionConflictEntryTime(SUMOTime_MAX),
    1020      4638859 :     myTimeSinceStartup(TIME2STEPS(3600 * 24)),
    1021      4638859 :     myHaveStoppedFor(nullptr),
    1022     13916577 :     myInfluencer(nullptr) {
    1023      4638859 :     myCFVariables = type->getCarFollowModel().createVehicleVariables();
    1024      4638859 :     myNextDriveItem = myLFLinkLanes.begin();
    1025      4638859 : }
    1026              : 
    1027              : 
    1028      8778918 : MSVehicle::~MSVehicle() {
    1029      4638779 :     cleanupFurtherLanes();
    1030      4638779 :     delete myLaneChangeModel;
    1031      4638779 :     if (myType->isVehicleSpecific()) {
    1032          316 :         MSNet::getInstance()->getVehicleControl().removeVType(myType);
    1033              :     }
    1034      4638779 :     delete myInfluencer;
    1035      4638779 :     delete myCFVariables;
    1036     13417697 : }
    1037              : 
    1038              : 
    1039              : void
    1040      4639341 : MSVehicle::cleanupFurtherLanes() {
    1041      4642183 :     for (MSLane* further : myFurtherLanes) {
    1042         2842 :         further->resetPartialOccupation(this);
    1043         2842 :         if (further->getBidiLane() != nullptr
    1044         2842 :                 && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    1045            0 :             further->getBidiLane()->resetPartialOccupation(this);
    1046              :         }
    1047              :     }
    1048      4639341 :     if (myLaneChangeModel != nullptr) {
    1049      4639307 :         removeApproachingInformation(myLFLinkLanes);
    1050      4639307 :         myLaneChangeModel->cleanupShadowLane();
    1051      4639307 :         myLaneChangeModel->cleanupTargetLane();
    1052              :         // still needed when calling resetPartialOccupation (getShadowLane) and when removing
    1053              :         // approach information from parallel links
    1054              :     }
    1055              :     myFurtherLanes.clear();
    1056              :     myFurtherLanesPosLat.clear();
    1057      4639341 : }
    1058              : 
    1059              : 
    1060              : void
    1061      2954223 : MSVehicle::onRemovalFromNet(const MSMoveReminder::Notification reason) {
    1062              : #ifdef DEBUG_ACTIONSTEPS
    1063              :     if (DEBUG_COND) {
    1064              :         std::cout << SIMTIME << " Removing vehicle '" << getID() << "' (reason: " << toString(reason) << ")" << std::endl;
    1065              :     }
    1066              : #endif
    1067      2954223 :     MSVehicleTransfer::getInstance()->remove(this);
    1068      2954223 :     removeApproachingInformation(myLFLinkLanes);
    1069      2954223 :     leaveLane(reason);
    1070      2954223 :     if (reason == MSMoveReminder::NOTIFICATION_VAPORIZED_COLLISION) {
    1071          562 :         cleanupFurtherLanes();
    1072              :     }
    1073      2954223 : }
    1074              : 
    1075              : 
    1076              : void
    1077      4638859 : MSVehicle::initDevices() {
    1078      4638859 :     MSBaseVehicle::initDevices();
    1079      4638847 :     myLaneChangeModel = MSAbstractLaneChangeModel::build(myType->getLaneChangeModel(), *this);
    1080      4638825 :     myDriverState = static_cast<MSDevice_DriverState*>(getDevice(typeid(MSDevice_DriverState)));
    1081      4638825 :     myFrictionDevice = static_cast<MSDevice_Friction*>(getDevice(typeid(MSDevice_Friction)));
    1082      4638825 : }
    1083              : 
    1084              : 
    1085              : // ------------ interaction with the route
    1086              : bool
    1087   2407576772 : MSVehicle::hasValidRouteStart(std::string& msg) {
    1088              :     // note: not a const method because getDepartLane may call updateBestLanes
    1089   2407576772 :     if (!(*myCurrEdge)->isTazConnector()) {
    1090   2407130132 :         if (myParameter->departLaneProcedure == DepartLaneDefinition::GIVEN) {
    1091     50471799 :             if ((*myCurrEdge)->getDepartLane(*this) == nullptr) {
    1092          122 :                 msg = "Invalid departlane definition for vehicle '" + getID() + "'.";
    1093           61 :                 if (myParameter->departLane >= (int)(*myCurrEdge)->getLanes().size()) {
    1094           11 :                     myRouteValidity |= ROUTE_START_INVALID_LANE;
    1095              :                 } else {
    1096           50 :                     myRouteValidity |= ROUTE_START_INVALID_PERMISSIONS;
    1097              :                 }
    1098           61 :                 return false;
    1099              :             }
    1100              :         } else {
    1101   2356658333 :             if ((*myCurrEdge)->allowedLanes(getVClass()) == nullptr) {
    1102          156 :                 msg = "Vehicle '" + getID() + "' is not allowed to depart on any lane of edge '" + (*myCurrEdge)->getID() + "'.";
    1103           78 :                 myRouteValidity |= ROUTE_START_INVALID_PERMISSIONS;
    1104           78 :                 return false;
    1105              :             }
    1106              :         }
    1107   2407129993 :         if (myParameter->departSpeedProcedure == DepartSpeedDefinition::GIVEN && myParameter->departSpeed > myType->getMaxSpeed() + SPEED_EPS) {
    1108           38 :             msg = "Departure speed for vehicle '" + getID() + "' is too high for the vehicle type '" + myType->getID() + "'.";
    1109           19 :             myRouteValidity |= ROUTE_START_INVALID_LANE;
    1110           19 :             return false;
    1111              :         }
    1112              :     }
    1113   2407576614 :     myRouteValidity &= ~(ROUTE_START_INVALID_LANE | ROUTE_START_INVALID_PERMISSIONS);
    1114   2407576614 :     return true;
    1115              : }
    1116              : 
    1117              : 
    1118              : bool
    1119    687720237 : MSVehicle::hasArrived() const {
    1120    687720237 :     return hasArrivedInternal(false);
    1121              : }
    1122              : 
    1123              : 
    1124              : bool
    1125   1384059103 : MSVehicle::hasArrivedInternal(bool oppositeTransformed) const {
    1126   2239432029 :     return ((myCurrEdge == myRoute->end() - 1 || (myParameter->arrivalEdge >= 0 && getRoutePosition() >= myParameter->arrivalEdge))
    1127    528722562 :             && (myStops.empty() || myStops.front().edge != myCurrEdge || myStops.front().getSpeed() > 0)
    1128    989714328 :             && ((myLaneChangeModel->isOpposite() && !oppositeTransformed) ? myLane->getLength() - myState.myPos : myState.myPos) > MIN2(myLane->getLength(), myArrivalPos) - POSITION_EPS
    1129   1393996768 :             && !isRemoteControlled());
    1130              : }
    1131              : 
    1132              : 
    1133              : bool
    1134      1722352 : MSVehicle::replaceRoute(ConstMSRoutePtr newRoute, const std::string& info, bool onInit, int offset, bool addRouteStops, bool removeStops, std::string* msgReturn) {
    1135      3444704 :     if (MSBaseVehicle::replaceRoute(newRoute, info, onInit, offset, addRouteStops, removeStops, msgReturn)) {
    1136              :         // update best lanes (after stops were added)
    1137      1722334 :         myLastBestLanesEdge = nullptr;
    1138      1722334 :         myLastBestLanesInternalLane = nullptr;
    1139      1722334 :         updateBestLanes(true, onInit ? (*myCurrEdge)->getLanes().front() : 0);
    1140              :         assert(!removeStops || haveValidStopEdges());
    1141      1722334 :         if (myStops.size() == 0) {
    1142      1689466 :             myStopDist = std::numeric_limits<double>::max();
    1143              :         }
    1144      1722334 :         return true;
    1145              :     }
    1146              :     return false;
    1147              : }
    1148              : 
    1149              : 
    1150              : // ------------ Interaction with move reminders
    1151              : void
    1152    676051550 : MSVehicle::workOnMoveReminders(double oldPos, double newPos, double newSpeed) {
    1153              :     // This erasure-idiom works for all stl-sequence-containers
    1154              :     // See Meyers: Effective STL, Item 9
    1155   1780757340 :     for (MoveReminderCont::iterator rem = myMoveReminders.begin(); rem != myMoveReminders.end();) {
    1156              :         // XXX: calling notifyMove with newSpeed seems not the best choice. For the ballistic update, the average speed is calculated and used
    1157              :         //      although a higher order quadrature-formula might be more adequate.
    1158              :         //      For the euler case (where the speed is considered constant for each time step) it is conceivable that
    1159              :         //      the current calculations may lead to systematic errors for large time steps (compared to reality). Refs. #2579
    1160   2209411580 :         if (!rem->first->notifyMove(*this, oldPos + rem->second, newPos + rem->second, MAX2(0., newSpeed))) {
    1161              : #ifdef _DEBUG
    1162              :             if (myTraceMoveReminders) {
    1163              :                 traceMoveReminder("notifyMove", rem->first, rem->second, false);
    1164              :             }
    1165              : #endif
    1166              :             rem = myMoveReminders.erase(rem);
    1167              :         } else {
    1168              : #ifdef _DEBUG
    1169              :             if (myTraceMoveReminders) {
    1170              :                 traceMoveReminder("notifyMove", rem->first, rem->second, true);
    1171              :             }
    1172              : #endif
    1173              :             ++rem;
    1174              :         }
    1175              :     }
    1176    676051550 :     if (myEnergyParams != nullptr) {
    1177              :         // TODO make the vehicle energy params a derived class which is a move reminder
    1178    129332696 :         myEnergyParams->setDynamicValues(isStopped() ? getNextStop().duration : -1, isParking(), getWaitingTime(), getAngle());
    1179              :     }
    1180    676051550 : }
    1181              : 
    1182              : 
    1183              : void
    1184       104098 : MSVehicle::workOnIdleReminders() {
    1185       104098 :     updateWaitingTime(0.);   // cf issue 2233
    1186              : 
    1187              :     // vehicle move reminders
    1188       130692 :     for (const auto& rem : myMoveReminders) {
    1189        26594 :         rem.first->notifyIdle(*this);
    1190              :     }
    1191              : 
    1192              :     // lane move reminders - for aggregated values
    1193       241472 :     for (MSMoveReminder* rem : getLane()->getMoveReminders()) {
    1194       137374 :         rem->notifyIdle(*this);
    1195              :     }
    1196       104098 : }
    1197              : 
    1198              : // XXX: consider renaming...
    1199              : void
    1200     17773882 : MSVehicle::adaptLaneEntering2MoveReminder(const MSLane& enteredLane) {
    1201              :     // save the old work reminders, patching the position information
    1202              :     //  add the information about the new offset to the old lane reminders
    1203     17773882 :     const double oldLaneLength = myLane->getLength();
    1204     50994322 :     for (auto& rem : myMoveReminders) {
    1205     33220440 :         rem.second += oldLaneLength;
    1206              : #ifdef _DEBUG
    1207              : //        if (rem->first==0) std::cout << "Null reminder (?!)" << std::endl;
    1208              : //        std::cout << "Adapted MoveReminder on lane " << ((rem->first->getLane()==0) ? "NULL" : rem->first->getLane()->getID()) <<" position to " << rem->second << std::endl;
    1209              :         if (myTraceMoveReminders) {
    1210              :             traceMoveReminder("adaptedPos", rem.first, rem.second, true);
    1211              :         }
    1212              : #endif
    1213              :     }
    1214     29659518 :     for (MSMoveReminder* const rem : enteredLane.getMoveReminders()) {
    1215     11885636 :         addReminder(rem);
    1216              :     }
    1217     17773882 : }
    1218              : 
    1219              : 
    1220              : // ------------ Other getter methods
    1221              : double
    1222    157543358 : MSVehicle::getSlope() const {
    1223    157543358 :     if (isParking() && getStops().begin()->parkingarea != nullptr) {
    1224         3901 :         return getStops().begin()->parkingarea->getVehicleSlope(*this);
    1225              :     }
    1226    157539457 :     if (myLane == nullptr) {
    1227              :         return 0;
    1228              :     }
    1229    157539457 :     const double posLat = myState.myPosLat; // @todo get rid of the '-'
    1230    157539457 :     Position p1 = getPosition();
    1231    157539457 :     Position p2 = getBackPosition();
    1232              :     if (p2 == Position::INVALID) {
    1233              :         // Handle special case of vehicle's back reaching out of the network
    1234            6 :         if (myFurtherLanes.size() > 0) {
    1235            6 :             p2 = myFurtherLanes.back()->geometryPositionAtOffset(0, -myFurtherLanesPosLat.back());
    1236              :             if (p2 == Position::INVALID) {
    1237              :                 // unsuitable lane geometry
    1238            0 :                 p2 = myLane->geometryPositionAtOffset(0, posLat);
    1239              :             }
    1240              :         } else {
    1241            0 :             p2 = myLane->geometryPositionAtOffset(0, posLat);
    1242              :         }
    1243              :     }
    1244    157539457 :     return (p1 != p2 ? RAD2DEG(p2.slopeTo2D(p1)) : myLane->getShape().slopeDegreeAtOffset(myLane->interpolateLanePosToGeometryPos(getPositionOnLane())));
    1245              : }
    1246              : 
    1247              : 
    1248              : Position
    1249    899947256 : MSVehicle::getPosition(const double offset) const {
    1250    899947256 :     if (myLane == nullptr) {
    1251              :         // when called in the context of GUI-Drawing, the simulation step is already incremented
    1252          174 :         if (myInfluencer != nullptr && myInfluencer->isRemoteAffected(MSNet::getInstance()->getCurrentTimeStep())) {
    1253           50 :             return myCachedPosition;
    1254              :         } else {
    1255          124 :             return Position::INVALID;
    1256              :         }
    1257              :     }
    1258    899947082 :     if (isParking()) {
    1259      4317690 :         if (myInfluencer != nullptr && myInfluencer->getLastAccessTimeStep() > getNextStopParameter()->started) {
    1260          150 :             return myCachedPosition;
    1261              :         }
    1262      4317540 :         if (myStops.begin()->parkingarea != nullptr) {
    1263        22601 :             return myStops.begin()->parkingarea->getVehiclePosition(*this);
    1264              :         } else {
    1265              :             // position beside the road
    1266      4294939 :             PositionVector shp = myLane->getEdge().getLanes()[0]->getShape();
    1267      8589758 :             shp.move2side(SUMO_const_laneWidth * (MSGlobals::gLefthand ? -1 : 1));
    1268      4294939 :             return shp.positionAtOffset(myLane->interpolateLanePosToGeometryPos(getPositionOnLane() + offset));
    1269      4294939 :         }
    1270              :     }
    1271    895629392 :     const bool changingLanes = myLaneChangeModel->isChangingLanes();
    1272   1781250419 :     const double posLat = (MSGlobals::gLefthand ? 1 : -1) * getLateralPositionOnLane();
    1273    895629392 :     if (offset == 0. && !changingLanes) {
    1274              :         if (myCachedPosition == Position::INVALID) {
    1275    680527838 :             myCachedPosition = validatePosition(myLane->geometryPositionAtOffset(myState.myPos, posLat));
    1276    680527838 :             if (MSNet::getInstance()->hasElevation() && MSGlobals::gSublane) {
    1277        58610 :                 interpolateLateralZ(myCachedPosition, myState.myPos, posLat);
    1278              :             }
    1279              :         }
    1280    889010466 :         return myCachedPosition;
    1281              :     }
    1282      6618926 :     Position result = validatePosition(myLane->geometryPositionAtOffset(getPositionOnLane() + offset, posLat), offset);
    1283      6618926 :     interpolateLateralZ(result, getPositionOnLane() + offset, posLat);
    1284      6618926 :     return result;
    1285              : }
    1286              : 
    1287              : 
    1288              : void
    1289      6958771 : MSVehicle::interpolateLateralZ(Position& pos, double offset, double posLat) const {
    1290      6958771 :     const MSLane* shadow = myLaneChangeModel->getShadowLane();
    1291      6958771 :     if (shadow != nullptr && pos != Position::INVALID) {
    1292              :         // ignore negative offset
    1293              :         const Position shadowPos = shadow->geometryPositionAtOffset(MAX2(0.0, offset));
    1294        59342 :         if (shadowPos != Position::INVALID && pos.z() != shadowPos.z()) {
    1295          133 :             const double centerDist = (myLane->getWidth() + shadow->getWidth()) * 0.5;
    1296          133 :             double relOffset = fabs(posLat) / centerDist;
    1297          133 :             double newZ = (1 - relOffset) * pos.z() + relOffset * shadowPos.z();
    1298              :             pos.setz(newZ);
    1299              :         }
    1300              :     }
    1301      6958771 : }
    1302              : 
    1303              : 
    1304              : double
    1305        96774 : MSVehicle::getDistanceToLeaveJunction() const {
    1306        96774 :     double result = getLength() - getPositionOnLane();
    1307        96774 :     if (myLane->isNormal()) {
    1308              :         return MAX2(0.0, result);
    1309              :     }
    1310          424 :     const MSLane* lane = myLane;
    1311          848 :     while (lane->isInternal()) {
    1312          424 :         result += lane->getLength();
    1313          424 :         lane = lane->getCanonicalSuccessorLane();
    1314              :     }
    1315              :     return result;
    1316              : }
    1317              : 
    1318              : 
    1319              : Position
    1320       103444 : MSVehicle::getPositionAlongBestLanes(double offset) const {
    1321              :     assert(MSGlobals::gUsingInternalLanes);
    1322       103444 :     if (!isOnRoad()) {
    1323            0 :         return Position::INVALID;
    1324              :     }
    1325       103444 :     const std::vector<MSLane*>& bestLanes = getBestLanesContinuation();
    1326              :     auto nextBestLane = bestLanes.begin();
    1327       103444 :     const bool opposite = myLaneChangeModel->isOpposite();
    1328       103444 :     double pos = opposite ? myLane->getLength() - myState.myPos : myState.myPos;
    1329       103444 :     const MSLane* lane = opposite ? myLane->getParallelOpposite() : getLane();
    1330              :     assert(lane != 0);
    1331              :     bool success = true;
    1332              : 
    1333       305421 :     while (offset > 0) {
    1334              :         // take into account lengths along internal lanes
    1335       308799 :         while (lane->isInternal() && offset > 0) {
    1336       106822 :             if (offset > lane->getLength() - pos) {
    1337         3569 :                 offset -= lane->getLength() - pos;
    1338         3569 :                 lane = lane->getLinkCont()[0]->getViaLaneOrLane();
    1339              :                 pos = 0.;
    1340         3569 :                 if (lane == nullptr) {
    1341              :                     success = false;
    1342              :                     offset = 0.;
    1343              :                 }
    1344              :             } else {
    1345       103253 :                 pos += offset;
    1346              :                 offset = 0;
    1347              :             }
    1348              :         }
    1349              :         // set nextBestLane to next non-internal lane
    1350       207112 :         while (nextBestLane != bestLanes.end() && *nextBestLane == nullptr) {
    1351              :             ++nextBestLane;
    1352              :         }
    1353       201977 :         if (offset > 0) {
    1354              :             assert(!lane->isInternal());
    1355              :             assert(lane == *nextBestLane);
    1356        98724 :             if (offset > lane->getLength() - pos) {
    1357        98541 :                 offset -= lane->getLength() - pos;
    1358              :                 ++nextBestLane;
    1359              :                 assert(nextBestLane == bestLanes.end() || *nextBestLane != 0);
    1360        98541 :                 if (nextBestLane == bestLanes.end()) {
    1361              :                     success = false;
    1362              :                     offset = 0.;
    1363              :                 } else {
    1364        98541 :                     const MSLink* link = lane->getLinkTo(*nextBestLane);
    1365              :                     assert(link != nullptr);
    1366              :                     lane = link->getViaLaneOrLane();
    1367              :                     pos = 0.;
    1368              :                 }
    1369              :             } else {
    1370          183 :                 pos += offset;
    1371              :                 offset = 0;
    1372              :             }
    1373              :         }
    1374              : 
    1375              :     }
    1376              : 
    1377       103444 :     if (success) {
    1378       103444 :         return lane->geometryPositionAtOffset(pos, -getLateralPositionOnLane());
    1379              :     } else {
    1380            0 :         return Position::INVALID;
    1381              :     }
    1382              : }
    1383              : 
    1384              : 
    1385              : double
    1386       698712 : MSVehicle::getMaxSpeedOnLane() const {
    1387       698712 :     if (myLane != nullptr) {
    1388       698712 :         return myLane->getVehicleMaxSpeed(this);
    1389              :     }
    1390            0 :     return myType->getMaxSpeed();
    1391              : }
    1392              : 
    1393              : 
    1394              : Position
    1395    687146764 : MSVehicle::validatePosition(Position result, double offset) const {
    1396              :     int furtherIndex = 0;
    1397    687146764 :     double lastLength = getPositionOnLane();
    1398    687146764 :     while (result == Position::INVALID) {
    1399      2871402 :         if (furtherIndex >= (int)myFurtherLanes.size()) {
    1400              :             //WRITE_WARNINGF(TL("Could not compute position for vehicle '%', time=%."), getID(), time2string(MSNet::getInstance()->getCurrentTimeStep()));
    1401              :             break;
    1402              :         }
    1403              :         //std::cout << SIMTIME << " veh=" << getID() << " lane=" << myLane->getID() << " pos=" << getPositionOnLane() << " posLat=" << getLateralPositionOnLane() << " offset=" << offset << " result=" << result << " i=" << furtherIndex << " further=" << myFurtherLanes.size() << "\n";
    1404      1971623 :         MSLane* further = myFurtherLanes[furtherIndex];
    1405      1971623 :         offset += lastLength;
    1406      1971623 :         result = further->geometryPositionAtOffset(further->getLength() + offset, -getLateralPositionOnLane());
    1407              :         lastLength = further->getLength();
    1408      1971623 :         furtherIndex++;
    1409              :         //std::cout << SIMTIME << "   newResult=" << result << "\n";
    1410              :     }
    1411    687146764 :     return result;
    1412              : }
    1413              : 
    1414              : 
    1415              : ConstMSEdgeVector::const_iterator
    1416      2646871 : MSVehicle::getRerouteOrigin() const {
    1417              :     // too close to the next junction, so avoid an emergency brake here
    1418      2646871 :     if (myLane != nullptr && (myCurrEdge + 1) != myRoute->end() && !isRailway(getVClass())) {
    1419       632607 :         if (myLane->isInternal()) {
    1420              :             return myCurrEdge + 1;
    1421              :         }
    1422       625634 :         if (myState.myPos > myLane->getLength() - getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0.)) {
    1423              :             return myCurrEdge + 1;
    1424              :         }
    1425       623113 :         if (myLane->getEdge().hasChangeProhibitions(getVClass(), myLane->getIndex())) {
    1426              :             return myCurrEdge + 1;
    1427              :         }
    1428              :     }
    1429      2637265 :     return myCurrEdge;
    1430              : }
    1431              : 
    1432              : void
    1433      5228878 : MSVehicle::setAngle(double angle, bool straightenFurther) {
    1434              : #ifdef DEBUG_FURTHER
    1435              :     if (DEBUG_COND) {
    1436              :         std::cout << SIMTIME << " veh '" << getID() << " setAngle(" << angle <<  ") straightenFurther=" << straightenFurther << std::endl;
    1437              :     }
    1438              : #endif
    1439      5228878 :     myAngle = angle;
    1440      5228878 :     MSLane* next = myLane;
    1441      5228878 :     if (straightenFurther && myFurtherLanesPosLat.size() > 0) {
    1442       196771 :         for (int i = 0; i < (int)myFurtherLanes.size(); i++) {
    1443       100930 :             MSLane* further = myFurtherLanes[i];
    1444       100930 :             const MSLink* link = further->getLinkTo(next);
    1445       100930 :             if (link  != nullptr) {
    1446       100546 :                 myFurtherLanesPosLat[i] = getLateralPositionOnLane() - link->getLateralShift();
    1447              :                 next = further;
    1448              :             } else {
    1449              :                 break;
    1450              :             }
    1451              :         }
    1452              :     }
    1453      5228878 : }
    1454              : 
    1455              : 
    1456              : void
    1457       406678 : MSVehicle::setActionStepLength(double actionStepLength, bool resetOffset) {
    1458       406678 :     SUMOTime actionStepLengthMillisecs = SUMOVehicleParserHelper::processActionStepLength(actionStepLength);
    1459              :     SUMOTime previousActionStepLength = getActionStepLength();
    1460              :     const bool newActionStepLength = actionStepLengthMillisecs != previousActionStepLength;
    1461       406678 :     if (newActionStepLength) {
    1462            7 :         getSingularType().setActionStepLength(actionStepLengthMillisecs, resetOffset);
    1463            7 :         if (!resetOffset) {
    1464            1 :             updateActionOffset(previousActionStepLength, actionStepLengthMillisecs);
    1465              :         }
    1466              :     }
    1467       406672 :     if (resetOffset) {
    1468            6 :         resetActionOffset();
    1469              :     }
    1470       406678 : }
    1471              : 
    1472              : 
    1473              : bool
    1474    293692159 : MSVehicle::congested() const {
    1475    293692159 :     return myState.mySpeed < (60.0 / 3.6) || myLane->getSpeedLimit() < (60.1 / 3.6);
    1476              : }
    1477              : 
    1478              : 
    1479              : double
    1480    683195175 : MSVehicle::computeAngle() const {
    1481              :     Position p1;
    1482    683195175 :     const double posLat = -myState.myPosLat; // @todo get rid of the '-'
    1483    683195175 :     const double lefthandSign = (MSGlobals::gLefthand ? -1 : 1);
    1484              : 
    1485              :     // if parking manoeuvre is happening then rotate vehicle on each step
    1486    683195175 :     if (MSGlobals::gModelParkingManoeuver && !manoeuvreIsComplete()) {
    1487          450 :         return getAngle() + myManoeuvre.getGUIIncrement();
    1488              :     }
    1489              : 
    1490    683194725 :     if (isParking()) {
    1491        27455 :         if (myStops.begin()->parkingarea != nullptr) {
    1492        15650 :             return myStops.begin()->parkingarea->getVehicleAngle(*this);
    1493              :         } else {
    1494        11805 :             return myLane->getShape().rotationAtOffset(myLane->interpolateLanePosToGeometryPos(getPositionOnLane()));
    1495              :         }
    1496              :     }
    1497    683167270 :     if (myLaneChangeModel->isChangingLanes()) {
    1498              :         // cannot use getPosition() because it already includes the offset to the side and thus messes up the angle
    1499      1124853 :         p1 = myLane->geometryPositionAtOffset(myState.myPos, lefthandSign * posLat);
    1500           12 :         if (p1 == Position::INVALID && myLane->getShape().length2D() == 0. && myLane->isInternal()) {
    1501              :             // workaround: extrapolate the preceding lane shape
    1502           12 :             MSLane* predecessorLane = myLane->getCanonicalPredecessorLane();
    1503           12 :             p1 = predecessorLane->geometryPositionAtOffset(predecessorLane->getLength() + myState.myPos, lefthandSign * posLat);
    1504              :         }
    1505              :     } else {
    1506    682042417 :         p1 = getPosition();
    1507              :     }
    1508              : 
    1509              :     Position p2;
    1510    683167270 :     if (getVehicleType().getParameter().locomotiveLength > 0) {
    1511              :         // articulated vehicle should use the heading of the first part
    1512      1731583 :         const double locoLength = MIN2(getVehicleType().getParameter().locomotiveLength, getLength());
    1513      1731583 :         p2 = getPosition(-locoLength);
    1514              :     } else {
    1515    681435687 :         p2 = getBackPosition();
    1516              :     }
    1517              :     if (p2 == Position::INVALID) {
    1518              :         // Handle special case of vehicle's back reaching out of the network
    1519          846 :         if (myFurtherLanes.size() > 0) {
    1520          126 :             p2 = myFurtherLanes.back()->geometryPositionAtOffset(0, -myFurtherLanesPosLat.back());
    1521              :             if (p2 == Position::INVALID) {
    1522              :                 // unsuitable lane geometry
    1523           78 :                 p2 = myLane->geometryPositionAtOffset(0, posLat);
    1524              :             }
    1525              :         } else {
    1526          720 :             p2 = myLane->geometryPositionAtOffset(0, posLat);
    1527              :         }
    1528              :     }
    1529              :     double result = (p1 != p2 ? p2.angleTo2D(p1) :
    1530        87508 :                      myLane->getShape().rotationAtOffset(myLane->interpolateLanePosToGeometryPos(getPositionOnLane())));
    1531              : 
    1532    683167270 :     result += lefthandSign * myLaneChangeModel->calcAngleOffset();
    1533              : 
    1534              : #ifdef DEBUG_FURTHER
    1535              :     if (DEBUG_COND) {
    1536              :         std::cout << SIMTIME << " computeAngle veh=" << getID() << " p1=" << p1 << " p2=" << p2 << " angle=" << RAD2DEG(result) << " naviDegree=" << GeomHelper::naviDegree(result) << "\n";
    1537              :     }
    1538              : #endif
    1539    683167270 :     return result;
    1540              : }
    1541              : 
    1542              : 
    1543              : const Position
    1544    845917773 : MSVehicle::getBackPosition() const {
    1545    845917773 :     const double posLat = MSGlobals::gLefthand ? myState.myPosLat : -myState.myPosLat;
    1546              :     Position result;
    1547    845917773 :     if (myState.myPos >= myType->getLength()) {
    1548              :         // vehicle is fully on the new lane
    1549    829702617 :         result = myLane->geometryPositionAtOffset(myState.myPos - myType->getLength(), posLat);
    1550              :     } else {
    1551     16215156 :         if (myLaneChangeModel->isChangingLanes() && myFurtherLanes.size() > 0 && myLaneChangeModel->getShadowLane(myFurtherLanes.back()) == nullptr) {
    1552              :             // special case where the target lane has no predecessor
    1553              : #ifdef DEBUG_FURTHER
    1554              :             if (DEBUG_COND) {
    1555              :                 std::cout << "    getBackPosition veh=" << getID() << " specialCase using myLane=" << myLane->getID() << " pos=0 posLat=" << myState.myPosLat << " result=" << myLane->geometryPositionAtOffset(0, posLat) << "\n";
    1556              :             }
    1557              : #endif
    1558         1701 :             result = myLane->geometryPositionAtOffset(0, posLat);
    1559              :         } else {
    1560              : #ifdef DEBUG_FURTHER
    1561              :             if (DEBUG_COND) {
    1562              :                 std::cout << "    getBackPosition veh=" << getID() << " myLane=" << myLane->getID() << " further=" << toString(myFurtherLanes) << " myFurtherLanesPosLat=" << toString(myFurtherLanesPosLat) << "\n";
    1563              :             }
    1564              : #endif
    1565     16213455 :             if (myFurtherLanes.size() > 0 && !myLaneChangeModel->isChangingLanes()) {
    1566              :                 // truncate to 0 if vehicle starts on an edge that is shorter than its length
    1567     15896160 :                 const double backPos = MAX2(0.0, getBackPositionOnLane(myFurtherLanes.back()));
    1568     31494780 :                 result = myFurtherLanes.back()->geometryPositionAtOffset(backPos, -myFurtherLanesPosLat.back() * (MSGlobals::gLefthand ? -1 : 1));
    1569              :             } else {
    1570       317295 :                 result = myLane->geometryPositionAtOffset(0, posLat);
    1571              :             }
    1572              :         }
    1573              :     }
    1574    845917773 :     if (MSNet::getInstance()->hasElevation() && MSGlobals::gSublane) {
    1575       281235 :         interpolateLateralZ(result, myState.myPos - myType->getLength(), posLat);
    1576              :     }
    1577    845917773 :     return result;
    1578              : }
    1579              : 
    1580              : 
    1581              : bool
    1582       458418 : MSVehicle::willStop() const {
    1583       458418 :     return !isStopped() && !myStops.empty() && myLane != nullptr && &myStops.front().lane->getEdge() == &myLane->getEdge();
    1584              : }
    1585              : 
    1586              : bool
    1587    357334409 : MSVehicle::isStoppedOnLane() const {
    1588    357334409 :     return isStopped() && myStops.front().lane == myLane;
    1589              : }
    1590              : 
    1591              : bool
    1592     30901409 : MSVehicle::keepStopping(bool afterProcessing) const {
    1593     30901409 :     if (isStopped()) {
    1594              :         // when coming out of vehicleTransfer we must shift the time forward
    1595     36811822 :         return (myStops.front().duration - (afterProcessing ? DELTA_T : 0) > 0 || isStoppedTriggered() || myStops.front().pars.collision
    1596     30696043 :                 || myStops.front().pars.breakDown || (myStops.front().getSpeed() > 0
    1597        36570 :                         && (myState.myPos < MIN2(myStops.front().pars.endPos, myStops.front().lane->getLength() - POSITION_EPS))
    1598        30726 :                         && (myStops.front().pars.parking == ParkingType::ONROAD || getSpeed() >= SUMO_const_haltingSpeed)));
    1599              :     } else {
    1600              :         return false;
    1601              :     }
    1602              : }
    1603              : 
    1604              : 
    1605              : SUMOTime
    1606        16133 : MSVehicle::remainingStopDuration() const {
    1607        16133 :     if (isStopped()) {
    1608        16133 :         return myStops.front().duration;
    1609              :     }
    1610              :     return 0;
    1611              : }
    1612              : 
    1613              : 
    1614              : SUMOTime
    1615    657929595 : MSVehicle::collisionStopTime() const {
    1616    657929595 :     return (myStops.empty() || !myStops.front().pars.collision) ? myCollisionImmunity : MAX2((SUMOTime)0, myStops.front().duration);
    1617              : }
    1618              : 
    1619              : 
    1620              : bool
    1621    657771072 : MSVehicle::brokeDown() const {
    1622    657771072 :     return isStopped() && !myStops.empty() && myStops.front().pars.breakDown;
    1623              : }
    1624              : 
    1625              : 
    1626              : bool
    1627       177769 : MSVehicle::ignoreCollision() const {
    1628       177769 :     return myCollisionImmunity > 0;
    1629              : }
    1630              : 
    1631              : 
    1632              : double
    1633    620087324 : MSVehicle::processNextStop(double currentVelocity) {
    1634    620087324 :     if (myStops.empty()) {
    1635              :         // no stops; pass
    1636              :         return currentVelocity;
    1637              :     }
    1638              : 
    1639              : #ifdef DEBUG_STOPS
    1640              :     if (DEBUG_COND) {
    1641              :         std::cout << "\nPROCESS_NEXT_STOP\n" << SIMTIME << " vehicle '" << getID() << "'" << std::endl;
    1642              :     }
    1643              : #endif
    1644              : 
    1645              :     MSStop& stop = myStops.front();
    1646     40742354 :     const SUMOTime time = MSNet::getInstance()->getCurrentTimeStep();
    1647     40742354 :     if (stop.reached) {
    1648     26244420 :         stop.duration -= getActionStepLength();
    1649              : 
    1650              : #ifdef DEBUG_STOPS
    1651              :         if (DEBUG_COND) {
    1652              :             std::cout << SIMTIME << " vehicle '" << getID() << "' reached stop.\n"
    1653              :                       << "Remaining duration: " << STEPS2TIME(stop.duration) << std::endl;
    1654              :             if (stop.getSpeed() > 0) {
    1655              :                 std::cout << " waypointSpeed=" << stop.getSpeed() << " vehPos=" << myState.myPos << " endPos=" << stop.pars.endPos << "\n";
    1656              :             }
    1657              :         }
    1658              : #endif
    1659     26244420 :         if (stop.duration <= 0 && stop.pars.join != "") {
    1660              :             // join this train (part) to another one
    1661        36414 :             MSVehicle* joinVeh = dynamic_cast<MSVehicle*>(MSNet::getInstance()->getVehicleControl().getVehicle(stop.pars.join));
    1662          969 :             if (joinVeh && joinVeh->hasDeparted() && (joinVeh->joinTrainPart(this) || joinVeh->joinTrainPartFront(this))) {
    1663           36 :                 stop.joinTriggered = false;
    1664           36 :                 if (myAmRegisteredAsWaiting) {
    1665           21 :                     MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    1666           21 :                     myAmRegisteredAsWaiting = false;
    1667              :                 }
    1668              :                 // avoid collision warning before this vehicle is removed (joinVeh was already made longer)
    1669           36 :                 myCollisionImmunity = TIME2STEPS(100);
    1670              :                 // mark this vehicle as arrived
    1671           36 :                 myArrivalPos = getPositionOnLane();
    1672           36 :                 const_cast<SUMOVehicleParameter*>(myParameter)->arrivalEdge = getRoutePosition();
    1673              :                 // handle transportables that want to continue in the other vehicle
    1674           36 :                 if (myPersonDevice != nullptr) {
    1675            3 :                     myPersonDevice->transferAtSplitOrJoin(joinVeh);
    1676              :                 }
    1677           36 :                 if (myContainerDevice != nullptr) {
    1678            3 :                     myContainerDevice->transferAtSplitOrJoin(joinVeh);
    1679              :                 }
    1680              :             }
    1681              :         }
    1682     26244420 :         boardTransportables(stop);
    1683     21969500 :         if (time > stop.endBoarding) {
    1684              :             // for taxi: cancel customers
    1685       223200 :             MSDevice_Taxi* taxiDevice = static_cast<MSDevice_Taxi*>(getDevice(typeid(MSDevice_Taxi)));
    1686              :             if (taxiDevice != nullptr) {
    1687              :                 // may invalidate stops including the current reference
    1688           64 :                 taxiDevice->cancelCurrentCustomers();
    1689           64 :                 resumeFromStopping();
    1690           64 :                 return currentVelocity;
    1691              :             }
    1692              :         }
    1693     21969436 :         if (!keepStopping() && isOnRoad()) {
    1694              : #ifdef DEBUG_STOPS
    1695              :             if (DEBUG_COND) {
    1696              :                 std::cout << SIMTIME << " vehicle '" << getID() << "' resumes from stopping." << std::endl;
    1697              :             }
    1698              : #endif
    1699        42444 :             resumeFromStopping();
    1700        42444 :             if (isRail() && hasStops()) {
    1701              :                 // stay on the current lane in case of a double stop
    1702         2786 :                 const MSStop& nextStop = getNextStop();
    1703         2786 :                 if (nextStop.edge == myCurrEdge) {
    1704         1033 :                     const double stopSpeed = getCarFollowModel().stopSpeed(this, getSpeed(), nextStop.pars.endPos - myState.myPos);
    1705              :                     //std::cout << SIMTIME << " veh=" << getID() << " resumedFromStopping currentVelocity=" << currentVelocity << " stopSpeed=" << stopSpeed << "\n";
    1706         1033 :                     return stopSpeed;
    1707              :                 }
    1708              :             }
    1709              :         } else {
    1710     21926992 :             if (stop.triggered) {
    1711      2988050 :                 if (getVehicleType().getPersonCapacity() == getPersonNumber()) {
    1712           30 :                     WRITE_WARNINGF(TL("Vehicle '%' ignores triggered stop on lane '%' due to capacity constraints."), getID(), stop.lane->getID());
    1713           10 :                     stop.triggered = false;
    1714      2988040 :                 } else if (!myAmRegisteredAsWaiting && stop.duration <= DELTA_T) {
    1715              :                     // we can only register after waiting for one step. otherwise we might falsely signal a deadlock
    1716         3205 :                     MSNet::getInstance()->getVehicleControl().registerOneWaiting();
    1717         3205 :                     myAmRegisteredAsWaiting = true;
    1718              : #ifdef DEBUG_STOPS
    1719              :                     if (DEBUG_COND) {
    1720              :                         std::cout << SIMTIME << " vehicle '" << getID() << "' registers as waiting for person." << std::endl;
    1721              :                     }
    1722              : #endif
    1723              :                 }
    1724              :             }
    1725     21926992 :             if (stop.containerTriggered) {
    1726        39493 :                 if (getVehicleType().getContainerCapacity() == getContainerNumber()) {
    1727         1311 :                     WRITE_WARNINGF(TL("Vehicle '%' ignores container triggered stop on lane '%' due to capacity constraints."), getID(), stop.lane->getID());
    1728          437 :                     stop.containerTriggered = false;
    1729        39056 :                 } else if (stop.containerTriggered && !myAmRegisteredAsWaiting && stop.duration <= DELTA_T) {
    1730              :                     // we can only register after waiting for one step. otherwise we might falsely signal a deadlock
    1731           92 :                     MSNet::getInstance()->getVehicleControl().registerOneWaiting();
    1732           92 :                     myAmRegisteredAsWaiting = true;
    1733              : #ifdef DEBUG_STOPS
    1734              :                     if (DEBUG_COND) {
    1735              :                         std::cout << SIMTIME << " vehicle '" << getID() << "' registers as waiting for container." << std::endl;
    1736              :                     }
    1737              : #endif
    1738              :                 }
    1739              :             }
    1740              :             // joining only takes place after stop duration is over
    1741     21926992 :             if (stop.joinTriggered && !myAmRegisteredAsWaiting
    1742         6509 :                     && stop.duration <= (stop.pars.extension >= 0 ? -stop.pars.extension : 0)) {
    1743           91 :                 if (stop.pars.extension >= 0) {
    1744           81 :                     WRITE_WARNINGF(TL("Vehicle '%' aborts joining after extension of %s at time %."), getID(), STEPS2TIME(stop.pars.extension), time2string(SIMSTEP));
    1745           27 :                     stop.joinTriggered = false;
    1746              :                 } else {
    1747              :                     // keep stopping indefinitely but ensure that simulation terminates
    1748           64 :                     MSNet::getInstance()->getVehicleControl().registerOneWaiting();
    1749           64 :                     myAmRegisteredAsWaiting = true;
    1750              :                 }
    1751              :             }
    1752     21926992 :             if (stop.getSpeed() > 0) {
    1753              :                 //waypoint mode
    1754       242923 :                 if (stop.duration == 0) {
    1755          266 :                     return stop.getSpeed();
    1756              :                 } else {
    1757              :                     // stop for 'until' (computed in planMove)
    1758              :                     return currentVelocity;
    1759              :                 }
    1760              :             } else {
    1761              :                 // brake
    1762     21684069 :                 if (MSGlobals::gSemiImplicitEulerUpdate || stop.getSpeed() > 0) {
    1763     21416897 :                     return 0;
    1764              :                 } else {
    1765              :                     // ballistic:
    1766       267172 :                     return getSpeed() - getCarFollowModel().getMaxDecel();
    1767              :                 }
    1768              :             }
    1769              :         }
    1770              :     } else {
    1771              : 
    1772              : #ifdef DEBUG_STOPS
    1773              :         if (DEBUG_COND) {
    1774              :             std::cout << SIMTIME << " vehicle '" << getID() << "' hasn't reached next stop." << std::endl;
    1775              :         }
    1776              : #endif
    1777              :         //std::cout << SIMTIME <<  " myStopDist=" << myStopDist << " bGap=" << getBrakeGap(myLane->getVehicleMaxSpeed(this)) << "\n";
    1778     14553623 :         if (stop.pars.onDemand && !stop.skipOnDemand && myStopDist <= getCarFollowModel().brakeGap(myLane->getVehicleMaxSpeed(this))) {
    1779          561 :             MSNet* const net = MSNet::getInstance();
    1780           44 :             const bool noExits = ((myPersonDevice == nullptr || !myPersonDevice->anyLeavingAtStop(stop))
    1781          571 :                                   && (myContainerDevice == nullptr || !myContainerDevice->anyLeavingAtStop(stop)));
    1782           83 :             const bool noEntries = ((!net->hasPersons() || !net->getPersonControl().hasAnyWaiting(stop.getEdge(), this))
    1783          610 :                                     && (!net->hasContainers() || !net->getContainerControl().hasAnyWaiting(stop.getEdge(), this)));
    1784          561 :             if (noExits && noEntries) {
    1785              :                 //std::cout << " skipOnDemand\n";
    1786          493 :                 stop.skipOnDemand = true;
    1787              :             }
    1788              :         }
    1789              :         // is the next stop on the current lane?
    1790     14497934 :         if (stop.edge == myCurrEdge) {
    1791              :             // get the stopping position
    1792      6146307 :             bool useStoppingPlace = stop.busstop != nullptr || stop.containerstop != nullptr || stop.parkingarea != nullptr;
    1793              :             bool fitsOnStoppingPlace = true;
    1794      6146307 :             if (!stop.skipOnDemand) {  // no need to check available space if we skip it anyway
    1795      6144372 :                 if (stop.busstop != nullptr) {
    1796      1650903 :                     fitsOnStoppingPlace &= stop.busstop->fits(myState.myPos, *this);
    1797              :                 }
    1798      6144372 :                 if (stop.containerstop != nullptr) {
    1799        21788 :                     fitsOnStoppingPlace &= stop.containerstop->fits(myState.myPos, *this);
    1800              :                 }
    1801              :                 // if the stop is a parking area we check if there is a free position on the area
    1802      6144372 :                 if (stop.parkingarea != nullptr) {
    1803       658350 :                     fitsOnStoppingPlace &= myState.myPos > stop.parkingarea->getBeginLanePosition();
    1804       658350 :                     if (stop.parkingarea->getOccupancy() >= stop.parkingarea->getCapacity()) {
    1805              :                         fitsOnStoppingPlace = false;
    1806              :                         // trigger potential parkingZoneReroute
    1807       426541 :                         MSParkingArea* oldParkingArea = stop.parkingarea;
    1808       457080 :                         for (MSMoveReminder* rem : myLane->getMoveReminders()) {
    1809        30539 :                             if (rem->isParkingRerouter()) {
    1810         9315 :                                 rem->notifyEnter(*this, MSMoveReminder::NOTIFICATION_PARKING_REROUTE, myLane);
    1811              :                             }
    1812              :                         }
    1813       426541 :                         if (myStops.empty() || myStops.front().parkingarea != oldParkingArea) {
    1814              :                             // rerouted, keep driving
    1815              :                             return currentVelocity;
    1816              :                         }
    1817       231809 :                     } else if (stop.parkingarea->getOccupancyIncludingReservations(this) >= stop.parkingarea->getCapacity()) {
    1818              :                         fitsOnStoppingPlace = false;
    1819       104824 :                     } else if (stop.parkingarea->parkOnRoad() && stop.parkingarea->getLotIndex(this) < 0) {
    1820              :                         fitsOnStoppingPlace = false;
    1821              :                     }
    1822              :                 }
    1823              :             }
    1824      6144315 :             const double targetPos = myState.myPos + myStopDist + (stop.getSpeed() > 0 ? (stop.pars.startPos - stop.pars.endPos) : 0);
    1825      6144315 :             const double reachedThreshold = (useStoppingPlace ? targetPos - STOPPING_PLACE_OFFSET : stop.getReachedThreshold()) - NUMERICAL_EPS;
    1826              : #ifdef DEBUG_STOPS
    1827              :             if (DEBUG_COND) {
    1828              :                 std::cout <<  "   pos=" << myState.pos() << " speed=" << currentVelocity << " targetPos=" << targetPos << " fits=" << fitsOnStoppingPlace
    1829              :                           << " reachedThresh=" << reachedThreshold
    1830              :                           << " myLane=" << Named::getIDSecure(myLane)
    1831              :                           << " stopLane=" << Named::getIDSecure(stop.lane)
    1832              :                           << "\n";
    1833              :             }
    1834              : #endif
    1835      6144315 :             const bool posReached = myState.pos() >= reachedThreshold && currentVelocity <= stop.getSpeed() + SUMO_const_haltingSpeed && myLane == stop.lane;
    1836      6144315 :             if (posReached && !fitsOnStoppingPlace && MSStopOut::active()) {
    1837         4505 :                 MSStopOut::getInstance()->stopBlocked(this, time);
    1838              :             }
    1839      6144315 :             if (fitsOnStoppingPlace && posReached && (!MSGlobals::gModelParkingManoeuver || myManoeuvre.entryManoeuvreIsComplete(this))) {
    1840              :                 // ok, we may stop (have reached the stop)  and either we are not modelling maneuvering or have completed entry
    1841        53813 :                 stop.reached = true;
    1842        53813 :                 if (!stop.startedFromState) {
    1843        53602 :                     stop.pars.started = time;
    1844              :                 }
    1845              : #ifdef DEBUG_STOPS
    1846              :                 if (DEBUG_COND) {
    1847              :                     std::cout << SIMTIME << " vehicle '" << getID() << "' reached next stop." << std::endl;
    1848              :                 }
    1849              : #endif
    1850        53813 :                 if (MSStopOut::active()) {
    1851         5072 :                     MSStopOut::getInstance()->stopStarted(this, getPersonNumber(), getContainerNumber(), time);
    1852              :                 }
    1853        53813 :                 myLane->getEdge().addWaiting(this);
    1854        53813 :                 MSNet::getInstance()->informVehicleStateListener(this, MSNet::VehicleState::STARTING_STOP);
    1855        53813 :                 MSNet::getInstance()->getVehicleControl().registerStopStarted();
    1856              :                 // compute stopping time
    1857        53813 :                 stop.duration = stop.getMinDuration(time);
    1858        53813 :                 stop.endBoarding = stop.pars.extension >= 0 ? time + stop.duration + stop.pars.extension : SUMOTime_MAX;
    1859        53813 :                 MSDevice_Taxi* taxiDevice = static_cast<MSDevice_Taxi*>(getDevice(typeid(MSDevice_Taxi)));
    1860         2699 :                 if (taxiDevice != nullptr && stop.pars.extension >= 0) {
    1861              :                     // earliestPickupTime is set with waitUntil
    1862           84 :                     stop.endBoarding = MAX2(time, stop.pars.waitUntil) + stop.pars.extension;
    1863              :                 }
    1864        53813 :                 if (stop.getSpeed() > 0) {
    1865              :                     // ignore duration parameter in waypoint mode unless 'until' or 'ended' are set
    1866         3265 :                     if (stop.getUntil() > time) {
    1867          334 :                         stop.duration = stop.getUntil() - time;
    1868              :                     } else {
    1869         2931 :                         stop.duration = 0;
    1870              :                     }
    1871              :                 }
    1872        53813 :                 if (stop.busstop != nullptr) {
    1873              :                     // let the bus stop know the vehicle
    1874        18078 :                     stop.busstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1875              :                 }
    1876        53813 :                 if (stop.containerstop != nullptr) {
    1877              :                     // let the container stop know the vehicle
    1878          569 :                     stop.containerstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1879              :                 }
    1880        53813 :                 if (stop.parkingarea != nullptr && stop.getSpeed() <= 0) {
    1881              :                     // let the parking area know the vehicle
    1882         8932 :                     stop.parkingarea->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1883              :                 }
    1884        53813 :                 if (stop.chargingStation != nullptr) {
    1885              :                     // let the container stop know the vehicle
    1886         3285 :                     stop.chargingStation->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1887              :                 }
    1888              : 
    1889        53813 :                 if (stop.pars.tripId != "") {
    1890         2568 :                     ((SUMOVehicleParameter&)getParameter()).setParameter("tripId", stop.pars.tripId);
    1891              :                 }
    1892        53813 :                 if (stop.pars.line != "") {
    1893         1288 :                     ((SUMOVehicleParameter&)getParameter()).line = stop.pars.line;
    1894              :                 }
    1895        53813 :                 if (stop.pars.split != "") {
    1896              :                     // split the train
    1897         1063 :                     MSVehicle* splitVeh = dynamic_cast<MSVehicle*>(MSNet::getInstance()->getVehicleControl().getVehicle(stop.pars.split));
    1898           24 :                     if (splitVeh == nullptr) {
    1899         3117 :                         WRITE_WARNINGF(TL("Vehicle '%' to split from vehicle '%' is not known. time=%."), stop.pars.split, getID(), SIMTIME)
    1900              :                     } else {
    1901           24 :                         MSNet::getInstance()->getInsertionControl().add(splitVeh);
    1902           24 :                         splitVeh->getRoute().getEdges()[0]->removeWaiting(splitVeh);
    1903           24 :                         MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    1904           24 :                         const double newLength = MAX2(myType->getLength() - splitVeh->getVehicleType().getLength(),
    1905           24 :                                                       myType->getParameter().locomotiveLength);
    1906           24 :                         getSingularType().setLength(newLength);
    1907              :                         // handle transportables that want to continue in the split part
    1908           24 :                         if (myPersonDevice != nullptr) {
    1909            0 :                             myPersonDevice->transferAtSplitOrJoin(splitVeh);
    1910              :                         }
    1911           24 :                         if (myContainerDevice != nullptr) {
    1912            6 :                             myContainerDevice->transferAtSplitOrJoin(splitVeh);
    1913              :                         }
    1914           24 :                         if (splitVeh->getParameter().departPosProcedure == DepartPosDefinition::SPLIT_FRONT) {
    1915            3 :                             const double backShift = splitVeh->getLength() + getVehicleType().getMinGap();
    1916            3 :                             myState.myPos -= backShift;
    1917            3 :                             myState.myBackPos -= backShift;
    1918              :                         }
    1919              :                     }
    1920              :                 }
    1921              : 
    1922        53813 :                 boardTransportables(stop);
    1923        53809 :                 if (stop.pars.posLat != INVALID_DOUBLE) {
    1924          231 :                     myState.myPosLat = stop.pars.posLat;
    1925              :                 }
    1926              :             }
    1927              :         }
    1928              :     }
    1929              :     return currentVelocity;
    1930              : }
    1931              : 
    1932              : 
    1933              : void
    1934     26298233 : MSVehicle::boardTransportables(MSStop& stop) {
    1935     26298233 :     if (stop.skipOnDemand) {
    1936              :         return;
    1937              :     }
    1938              :     // we have reached the stop
    1939              :     // any waiting persons may board now
    1940     26071168 :     const SUMOTime time = MSNet::getInstance()->getCurrentTimeStep();
    1941     26071168 :     MSNet* const net = MSNet::getInstance();
    1942     26071168 :     const bool boarded = (time <= stop.endBoarding
    1943     26069086 :                           && net->hasPersons()
    1944      1203844 :                           && net->getPersonControl().loadAnyWaiting(&myLane->getEdge(), this, stop.timeToBoardNextPerson, stop.duration)
    1945     26075849 :                           && stop.numExpectedPerson == 0);
    1946              :     // load containers
    1947     26071168 :     const bool loaded = (time <= stop.endBoarding
    1948     26069086 :                          && net->hasContainers()
    1949      4377342 :                          && net->getContainerControl().loadAnyWaiting(&myLane->getEdge(), this, stop.timeToLoadNextContainer, stop.duration)
    1950     26071743 :                          && stop.numExpectedContainer == 0);
    1951              : 
    1952              :     bool unregister = false;
    1953     21796244 :     if (time > stop.endBoarding) {
    1954         2082 :         stop.triggered = false;
    1955         2082 :         stop.containerTriggered = false;
    1956         2082 :         if (myAmRegisteredAsWaiting) {
    1957              :             unregister = true;
    1958          332 :             myAmRegisteredAsWaiting = false;
    1959              :         }
    1960              :     }
    1961     21796244 :     if (boarded) {
    1962              :         // the triggering condition has been fulfilled. Maybe we want to wait a bit longer for additional riders (car pooling)
    1963         4550 :         if (myAmRegisteredAsWaiting) {
    1964              :             unregister = true;
    1965              :         }
    1966         4550 :         stop.triggered = false;
    1967         4550 :         myAmRegisteredAsWaiting = false;
    1968              :     }
    1969     21796244 :     if (loaded) {
    1970              :         // the triggering condition has been fulfilled
    1971          555 :         if (myAmRegisteredAsWaiting) {
    1972              :             unregister = true;
    1973              :         }
    1974          555 :         stop.containerTriggered = false;
    1975          555 :         myAmRegisteredAsWaiting = false;
    1976              :     }
    1977              : 
    1978     21796244 :     if (unregister) {
    1979          416 :         MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    1980              : #ifdef DEBUG_STOPS
    1981              :         if (DEBUG_COND) {
    1982              :             std::cout << SIMTIME << " vehicle '" << getID() << "' unregisters as waiting for transportable." << std::endl;
    1983              :         }
    1984              : #endif
    1985              :     }
    1986              : }
    1987              : 
    1988              : bool
    1989          921 : MSVehicle::joinTrainPart(MSVehicle* veh) {
    1990              :     // check if veh is close enough to be joined to the rear of this vehicle
    1991          921 :     MSLane* backLane = myFurtherLanes.size() == 0 ? myLane : myFurtherLanes.back();
    1992          921 :     double gap = getBackPositionOnLane() - veh->getPositionOnLane();
    1993         1144 :     if (isStopped() && myStops.begin()->duration <= DELTA_T && myStops.begin()->joinTriggered && backLane == veh->getLane()
    1994          951 :             && gap >= 0 && gap <= getVehicleType().getMinGap() + 1) {
    1995           15 :         const double newLength = myType->getLength() + veh->getVehicleType().getLength();
    1996           15 :         getSingularType().setLength(newLength);
    1997           15 :         myStops.begin()->joinTriggered = false;
    1998           15 :         if (myAmRegisteredAsWaiting) {
    1999            0 :             MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    2000            0 :             myAmRegisteredAsWaiting = false;
    2001              :         }
    2002              :         return true;
    2003              :     } else {
    2004          906 :         return false;
    2005              :     }
    2006              : }
    2007              : 
    2008              : 
    2009              : bool
    2010          906 : MSVehicle::joinTrainPartFront(MSVehicle* veh) {
    2011              :     // check if veh is close enough to be joined to the front of this vehicle
    2012          906 :     MSLane* backLane = veh->myFurtherLanes.size() == 0 ? veh->myLane : veh->myFurtherLanes.back();
    2013          906 :     double gap = veh->getBackPositionOnLane(backLane) - getPositionOnLane();
    2014         1114 :     if (isStopped() && myStops.begin()->duration <= DELTA_T && myStops.begin()->joinTriggered && backLane == getLane()
    2015          930 :             && gap >= 0 && gap <= getVehicleType().getMinGap() + 1) {
    2016              :         double skippedLaneLengths = 0;
    2017           24 :         if (veh->myFurtherLanes.size() > 0) {
    2018            9 :             skippedLaneLengths += getLane()->getLength();
    2019              :             // this vehicle must be moved to the lane of veh
    2020              :             // ensure that lane and furtherLanes of veh match our route
    2021            9 :             int routeIndex = getRoutePosition();
    2022            9 :             if (myLane->isInternal()) {
    2023            0 :                 routeIndex++;
    2024              :             }
    2025           27 :             for (int i = (int)veh->myFurtherLanes.size() - 1; i >= 0; i--) {
    2026           18 :                 MSEdge* edge = &veh->myFurtherLanes[i]->getEdge();
    2027           18 :                 if (edge->isInternal()) {
    2028            9 :                     continue;
    2029              :                 }
    2030            9 :                 if (!edge->isInternal() && edge != myRoute->getEdges()[routeIndex]) {
    2031            0 :                     std::string warn = TL("Cannot join vehicle '%' to vehicle '%' due to incompatible routes. time=%.");
    2032            0 :                     WRITE_WARNINGF(warn, veh->getID(), getID(), time2string(SIMSTEP));
    2033              :                     return false;
    2034              :                 }
    2035            9 :                 routeIndex++;
    2036              :             }
    2037            9 :             if (veh->getCurrentEdge()->getNormalSuccessor() != myRoute->getEdges()[routeIndex]) {
    2038            3 :                 std::string warn = TL("Cannot join vehicle '%' to vehicle '%' due to incompatible routes. time=%.");
    2039            9 :                 WRITE_WARNINGF(warn, veh->getID(), getID(), time2string(SIMSTEP));
    2040              :                 return false;
    2041              :             }
    2042           12 :             for (int i = (int)veh->myFurtherLanes.size() - 2; i >= 0; i--) {
    2043            6 :                 skippedLaneLengths += veh->myFurtherLanes[i]->getLength();
    2044              :             }
    2045              :         }
    2046              : 
    2047           21 :         const double newLength = myType->getLength() + veh->getVehicleType().getLength();
    2048           21 :         getSingularType().setLength(newLength);
    2049              :         // lane will be advanced just as for regular movement
    2050           21 :         myState.myPos = skippedLaneLengths + veh->getPositionOnLane();
    2051           21 :         myStops.begin()->joinTriggered = false;
    2052           21 :         if (myAmRegisteredAsWaiting) {
    2053            7 :             MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    2054            7 :             myAmRegisteredAsWaiting = false;
    2055              :         }
    2056           21 :         return true;
    2057              :     } else {
    2058          882 :         return false;
    2059              :     }
    2060              : }
    2061              : 
    2062              : double
    2063      9245409 : MSVehicle::getBrakeGap(bool delayed) const {
    2064      9245409 :     return getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), delayed ? getCarFollowModel().getHeadwayTime() : 0);
    2065              : }
    2066              : 
    2067              : 
    2068              : bool
    2069    680112409 : MSVehicle::checkActionStep(const SUMOTime t) {
    2070    680112409 :     myActionStep = isActionStep(t);
    2071    680112409 :     if (myActionStep) {
    2072    608595485 :         myLastActionTime = t;
    2073              :     }
    2074    680112409 :     return myActionStep;
    2075              : }
    2076              : 
    2077              : 
    2078              : void
    2079         1601 : MSVehicle::resetActionOffset(const SUMOTime timeUntilNextAction) {
    2080         1601 :     myLastActionTime = MSNet::getInstance()->getCurrentTimeStep() + timeUntilNextAction;
    2081         1601 : }
    2082              : 
    2083              : 
    2084              : void
    2085            1 : MSVehicle::updateActionOffset(const SUMOTime oldActionStepLength, const SUMOTime newActionStepLength) {
    2086            1 :     SUMOTime now = MSNet::getInstance()->getCurrentTimeStep();
    2087            1 :     SUMOTime timeSinceLastAction = now - myLastActionTime;
    2088            1 :     if (timeSinceLastAction == 0) {
    2089              :         // Action was scheduled now, may be delayed be new action step length
    2090              :         timeSinceLastAction = oldActionStepLength;
    2091              :     }
    2092            1 :     if (timeSinceLastAction >= newActionStepLength) {
    2093              :         // Action point required in this step
    2094            0 :         myLastActionTime = now;
    2095              :     } else {
    2096            1 :         SUMOTime timeUntilNextAction = newActionStepLength - timeSinceLastAction;
    2097            1 :         resetActionOffset(timeUntilNextAction);
    2098              :     }
    2099            1 : }
    2100              : 
    2101              : 
    2102              : 
    2103              : void
    2104    680112409 : MSVehicle::planMove(const SUMOTime t, const MSLeaderInfo& ahead, const double lengthsInFront) {
    2105              : #ifdef DEBUG_PLAN_MOVE
    2106              :     if (DEBUG_COND) {
    2107              :         std::cout
    2108              :                 << "\nPLAN_MOVE\n"
    2109              :                 << SIMTIME
    2110              :                 << std::setprecision(gPrecision)
    2111              :                 << " veh=" << getID()
    2112              :                 << " lane=" << myLane->getID()
    2113              :                 << " pos=" << getPositionOnLane()
    2114              :                 << " posLat=" << getLateralPositionOnLane()
    2115              :                 << " speed=" << getSpeed()
    2116              :                 << "\n";
    2117              :     }
    2118              : #endif
    2119              :     // Update the driver state
    2120    680112409 :     if (hasDriverState()) {
    2121       406664 :         myDriverState->update();
    2122       813328 :         setActionStepLength(myDriverState->getDriverState()->getActionStepLength(), false);
    2123              :     }
    2124              : 
    2125    680112409 :     if (!checkActionStep(t)) {
    2126              : #ifdef DEBUG_ACTIONSTEPS
    2127              :         if (DEBUG_COND) {
    2128              :             std::cout << STEPS2TIME(t) << " vehicle '" << getID() << "' skips action." << std::endl;
    2129              :         }
    2130              : #endif
    2131              :         // During non-action passed drive items still need to be removed
    2132              :         // @todo rather work with updating myCurrentDriveItem (refs #3714)
    2133     71516924 :         removePassedDriveItems();
    2134     71516924 :         return;
    2135              :     } else {
    2136              : #ifdef DEBUG_ACTIONSTEPS
    2137              :         if (DEBUG_COND) {
    2138              :             std::cout << STEPS2TIME(t) << " vehicle = '" << getID() << "' takes action." << std::endl;
    2139              :         }
    2140              : #endif
    2141    608595485 :         myLFLinkLanesPrev = myLFLinkLanes;
    2142    608595485 :         if (myInfluencer != nullptr) {
    2143       495467 :             myInfluencer->updateRemoteControlRoute(this);
    2144              :         }
    2145    608595485 :         planMoveInternal(t, ahead, myLFLinkLanes, myStopDist, myNextTurn);
    2146              : #ifdef DEBUG_PLAN_MOVE
    2147              :         if (DEBUG_COND) {
    2148              :             DriveItemVector::iterator i;
    2149              :             for (i = myLFLinkLanes.begin(); i != myLFLinkLanes.end(); ++i) {
    2150              :                 std::cout
    2151              :                         << " vPass=" << (*i).myVLinkPass
    2152              :                         << " vWait=" << (*i).myVLinkWait
    2153              :                         << " linkLane=" << ((*i).myLink == 0 ? "NULL" : (*i).myLink->getViaLaneOrLane()->getID())
    2154              :                         << " request=" << (*i).mySetRequest
    2155              :                         << "\n";
    2156              :             }
    2157              :         }
    2158              : #endif
    2159    608595485 :         checkRewindLinkLanes(lengthsInFront, myLFLinkLanes);
    2160    608595485 :         myNextDriveItem = myLFLinkLanes.begin();
    2161              :         // ideally would only do this with the call inside planMoveInternal - but that needs a const method
    2162              :         //   so this is a kludge here - nuisance as it adds an extra check in a busy loop
    2163    608595485 :         if (MSGlobals::gModelParkingManoeuver) {
    2164         2971 :             if (getManoeuvreType() == MSVehicle::MANOEUVRE_EXIT && manoeuvreIsComplete()) {
    2165           30 :                 setManoeuvreType(MSVehicle::MANOEUVRE_NONE);
    2166              :             }
    2167              :         }
    2168              :     }
    2169    608595485 :     myLaneChangeModel->resetChanged();
    2170              : }
    2171              : 
    2172              : 
    2173              : bool
    2174    169290754 : MSVehicle::brakeForOverlap(const MSLink* link, const MSLane* lane) const {
    2175              :     // @review needed
    2176              :     //const double futurePosLat = getLateralPositionOnLane() + link->getLateralShift();
    2177              :     //const double overlap = getLateralOverlap(futurePosLat, link->getViaLaneOrLane());
    2178              :     //const double edgeWidth = link->getViaLaneOrLane()->getEdge().getWidth();
    2179    169290754 :     const double futurePosLat = getLateralPositionOnLane() + (
    2180    169290754 :                                     lane != myLane && lane->isInternal() ? lane->getIncomingLanes()[0].viaLink->getLateralShift() : 0);
    2181    169290754 :     const double overlap = getLateralOverlap(futurePosLat, lane);
    2182              :     const double edgeWidth = lane->getEdge().getWidth();
    2183              :     const bool result = (overlap > POSITION_EPS
    2184              :                          // do not get stuck on narrow edges
    2185      3040491 :                          && getVehicleType().getWidth() <= edgeWidth
    2186      3036206 :                          && link->getViaLane() == nullptr
    2187              :                          // this is the exit link of a junction. The normal edge should support the shadow
    2188      1483856 :                          && ((myLaneChangeModel->getShadowLane(link->getLane()) == nullptr)
    2189              :                              // the shadow lane must be permitted
    2190      1092457 :                              || !myLaneChangeModel->getShadowLane(link->getLane())->allowsVehicleClass(getVClass())
    2191              :                              // the internal lane after an internal junction has no parallel lane. make sure there is no shadow before continuing
    2192      1032791 :                              || (lane->getEdge().isInternal() && lane->getIncomingLanes()[0].lane->getEdge().isInternal()))
    2193              :                          // ignore situations where the shadow lane is part of a double-connection with the current lane
    2194       467451 :                          && (myLaneChangeModel->getShadowLane() == nullptr
    2195       244345 :                              || myLaneChangeModel->getShadowLane()->getLinkCont().size() == 0
    2196       233415 :                              || myLaneChangeModel->getShadowLane()->getLinkCont().front()->getLane() != link->getLane())
    2197              :                          // emergency vehicles may do some crazy stuff
    2198    169696365 :                          && !myLaneChangeModel->hasBlueLight());
    2199              : 
    2200              : #ifdef DEBUG_PLAN_MOVE
    2201              :     if (DEBUG_COND) {
    2202              :         std::cout << SIMTIME << " veh=" << getID() << " link=" << link->getDescription() << " lane=" << lane->getID()
    2203              :                   << " linkLane=" << link->getLane()->getID()
    2204              :                   << " shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane())
    2205              :                   << " shift=" << link->getLateralShift()
    2206              :                   << " fpLat=" << futurePosLat << " overlap=" << overlap << " w=" << getVehicleType().getWidth()
    2207              :                   << " shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane(link->getLane()))
    2208              :                   << " result=" << result << "\n";
    2209              :     }
    2210              : #endif
    2211    169290754 :     return result;
    2212              : }
    2213              : 
    2214              : 
    2215              : 
    2216              : void
    2217    608595485 : MSVehicle::planMoveInternal(const SUMOTime t, MSLeaderInfo ahead, DriveItemVector& lfLinks, double& newStopDist, std::pair<double, const MSLink*>& nextTurn) const {
    2218              :     lfLinks.clear();
    2219    608595485 :     newStopDist = std::numeric_limits<double>::max();
    2220              :     //
    2221              :     const MSCFModel& cfModel = getCarFollowModel();
    2222    608595485 :     const double vehicleLength = getVehicleType().getLength();
    2223    608595485 :     const double maxV = cfModel.maxNextSpeed(myState.mySpeed, this);
    2224    608595485 :     const double maxVD = MAX2(getMaxSpeed(), MIN2(maxV, getDesiredMaxSpeed()));
    2225    608595485 :     const bool opposite = myLaneChangeModel->isOpposite();
    2226              :     // maxVD is possibly higher than vType-maxSpeed and in this case laneMaxV may be higher as well
    2227    608595485 :     double laneMaxV = myLane->getVehicleMaxSpeed(this, maxVD);
    2228    608595485 :     const double vMinComfortable = cfModel.minNextSpeed(getSpeed(), this);
    2229              :     double lateralShift = 0;
    2230    608595485 :     if (isRail()) {
    2231              :         // speed limits must hold for the whole length of the train
    2232      1561766 :         for (MSLane* l : myFurtherLanes) {
    2233       339509 :             laneMaxV = MIN2(laneMaxV, l->getVehicleMaxSpeed(this, maxVD));
    2234              : #ifdef DEBUG_PLAN_MOVE
    2235              :             if (DEBUG_COND) {
    2236              :                 std::cout << "   laneMaxV=" << laneMaxV << " lane=" << l->getID() << "\n";
    2237              :             }
    2238              : #endif
    2239              :         }
    2240              :     }
    2241              :     //  speed limits are not emergencies (e.g. when the limit changes suddenly due to TraCI or a variableSpeedSignal)
    2242              :     laneMaxV = MAX2(laneMaxV, vMinComfortable);
    2243    609090920 :     if (myInfluencer && !myInfluencer->considerSpeedLimit()) {
    2244              :         laneMaxV = std::numeric_limits<double>::max();
    2245              :     }
    2246              :     // v is the initial maximum velocity of this vehicle in this step
    2247    608595485 :     double v = cfModel.maximumLaneSpeedCF(this, maxV, laneMaxV);
    2248              :     // if we are modelling parking then we dawdle until the manoeuvre is complete - by setting a very low max speed
    2249              :     //   in practice this only applies to exit manoeuvre because entry manoeuvre just delays setting stop.reached - when the vehicle is virtually stopped
    2250    608595485 :     if (MSGlobals::gModelParkingManoeuver && !manoeuvreIsComplete()) {
    2251          420 :         v = NUMERICAL_EPS_SPEED;
    2252              :     }
    2253              : 
    2254    608595485 :     if (myInfluencer != nullptr) {
    2255       495467 :         const double vMin = MAX2(0., cfModel.minNextSpeed(myState.mySpeed, this));
    2256              : #ifdef DEBUG_TRACI
    2257              :         if (DEBUG_COND) {
    2258              :             std::cout << SIMTIME << " veh=" << getID() << " speedBeforeTraci=" << v;
    2259              :         }
    2260              : #endif
    2261       495467 :         v = myInfluencer->influenceSpeed(t, v, v, vMin, maxV);
    2262              : #ifdef DEBUG_TRACI
    2263              :         if (DEBUG_COND) {
    2264              :             std::cout << " influencedSpeed=" << v;
    2265              :         }
    2266              : #endif
    2267       495467 :         v = myInfluencer->gapControlSpeed(t, this, v, v, vMin, maxV);
    2268              : #ifdef DEBUG_TRACI
    2269              :         if (DEBUG_COND) {
    2270              :             std::cout << " gapControlSpeed=" << v << "\n";
    2271              :         }
    2272              : #endif
    2273              :     }
    2274              :     // all links within dist are taken into account (potentially)
    2275    608595485 :     const double dist = SPEED2DIST(maxV) + cfModel.brakeGap(maxV);
    2276              : 
    2277    608595485 :     const std::vector<MSLane*>& bestLaneConts = getBestLanesContinuation();
    2278              : #ifdef DEBUG_PLAN_MOVE
    2279              :     if (DEBUG_COND) {
    2280              :         std::cout << "   dist=" << dist << " bestLaneConts=" << toString(bestLaneConts)
    2281              :                   << "\n   maxV=" << maxV << " laneMaxV=" << laneMaxV << " v=" << v << "\n";
    2282              :     }
    2283              : #endif
    2284              :     assert(bestLaneConts.size() > 0);
    2285              :     bool hadNonInternal = false;
    2286              :     // the distance already "seen"; in the following always up to the end of the current "lane"
    2287    608595485 :     double seen = opposite ? myState.myPos : myLane->getLength() - myState.myPos;
    2288    608595485 :     nextTurn.first = seen;
    2289    608595485 :     nextTurn.second = nullptr;
    2290    608595485 :     bool encounteredTurn = (MSGlobals::gLateralResolution <= 0); // next turn is only needed for sublane
    2291              :     double seenNonInternal = 0;
    2292    608595485 :     double seenInternal = myLane->isInternal() ? seen : 0;
    2293    608595485 :     double vLinkPass = MIN2(cfModel.estimateSpeedAfterDistance(seen, v, cfModel.getMaxAccel()), laneMaxV); // upper bound
    2294              :     int view = 0;
    2295              :     DriveProcessItem* lastLink = nullptr;
    2296              :     bool slowedDownForMinor = false; // whether the vehicle already had to slow down on approach to a minor link
    2297              :     double mustSeeBeforeReversal = 0;
    2298              :     // iterator over subsequent lanes and fill lfLinks until stopping distance or stopped
    2299    608595485 :     const MSLane* lane = opposite ? myLane->getParallelOpposite() : myLane;
    2300              :     assert(lane != 0);
    2301    608595485 :     const MSLane* leaderLane = myLane;
    2302    608595485 :     bool foundRailSignal = !isRail();
    2303              :     bool planningToStop = false;
    2304              : #ifdef PARALLEL_STOPWATCH
    2305              :     myLane->getStopWatch()[0].start();
    2306              : #endif
    2307              : 
    2308              :     // optionally slow down to match arrival time
    2309    608595485 :     const double sfp = getVehicleType().getParameter().speedFactorPremature;
    2310    608584709 :     if (v > vMinComfortable && hasStops() && myStops.front().pars.arrival >= 0 && sfp > 0
    2311         4279 :             && v > myLane->getSpeedLimit() * sfp
    2312    608598521 :             && !myStops.front().reached) {
    2313         2786 :         const double vSlowDown = slowDownForSchedule(vMinComfortable);
    2314         5403 :         v = MIN2(v, vSlowDown);
    2315              :     }
    2316              :     auto stopIt = myStops.begin();
    2317              :     while (true) {
    2318              :         // check leader on lane
    2319              :         //  leader is given for the first edge only
    2320   1151909368 :         if (opposite &&
    2321              :                 (leaderLane->getVehicleNumberWithPartials() > 1
    2322       100254 :                  || (leaderLane != myLane && leaderLane->getVehicleNumber() > 0))) {
    2323       401152 :             ahead.clear();
    2324              :             // find opposite-driving leader that must be respected on the currently looked at lane
    2325              :             // (only looking at one lane at a time)
    2326       401152 :             const double backOffset = leaderLane == myLane ? getPositionOnLane() : leaderLane->getLength();
    2327       401152 :             const double gapOffset = leaderLane == myLane ? 0 : seen - leaderLane->getLength();
    2328       401152 :             const MSLeaderDistanceInfo cands = leaderLane->getFollowersOnConsecutive(this, backOffset, true, backOffset, MSLane::MinorLinkMode::FOLLOW_NEVER);
    2329       401152 :             MSLeaderDistanceInfo oppositeLeaders(leaderLane->getWidth(), this, 0.);
    2330       401152 :             const double minTimeToLeaveLane = MSGlobals::gSublane ? MAX2(TS, (0.5 *  myLane->getWidth() - getLateralPositionOnLane()) / getVehicleType().getMaxSpeedLat()) : TS;
    2331      1065268 :             for (int i = 0; i < cands.numSublanes(); i++) {
    2332       664116 :                 CLeaderDist cand = cands[i];
    2333       664116 :                 if (cand.first != 0) {
    2334       567868 :                     if ((cand.first->myLaneChangeModel->isOpposite() && cand.first->getLaneChangeModel().getShadowLane() != leaderLane)
    2335       568342 :                             || (!cand.first->myLaneChangeModel->isOpposite() && cand.first->getLaneChangeModel().getShadowLane() == leaderLane)) {
    2336              :                         // respect leaders that also drive in the opposite direction (fully or with some overlap)
    2337       358281 :                         oppositeLeaders.addLeader(cand.first, cand.second + gapOffset - getVehicleType().getMinGap() + cand.first->getVehicleType().getMinGap() - cand.first->getVehicleType().getLength());
    2338              :                     } else {
    2339              :                         // avoid frontal collision
    2340       385100 :                         const bool assumeStopped = cand.first->isStopped() || cand.first->getWaitingSeconds() > 1;
    2341       209587 :                         const double predMaxDist = cand.first->getSpeed() + (assumeStopped ? 0 : cand.first->getCarFollowModel().getMaxAccel()) * minTimeToLeaveLane;
    2342       209587 :                         if (cand.second >= 0 && (cand.second - v * minTimeToLeaveLane - predMaxDist < 0 || assumeStopped)) {
    2343        48138 :                             oppositeLeaders.addLeader(cand.first, cand.second + gapOffset - predMaxDist - getVehicleType().getMinGap());
    2344              :                         }
    2345              :                     }
    2346              :                 }
    2347              :             }
    2348              : #ifdef DEBUG_PLAN_MOVE
    2349              :             if (DEBUG_COND) {
    2350              :                 std::cout <<  " leaderLane=" << leaderLane->getID() << " gapOffset=" << gapOffset << " minTimeToLeaveLane=" << minTimeToLeaveLane
    2351              :                           << " cands=" << cands.toString() << " oppositeLeaders=" <<  oppositeLeaders.toString() << "\n";
    2352              :             }
    2353              : #endif
    2354       401152 :             adaptToLeaderDistance(oppositeLeaders, 0, seen, lastLink, v, vLinkPass);
    2355       401152 :         } else {
    2356   1151508216 :             if (MSGlobals::gLateralResolution > 0 && myLaneChangeModel->getShadowLane() == nullptr) {
    2357    191833706 :                 const double rightOL = getRightSideOnLane(lane) + lateralShift;
    2358    191833706 :                 const double leftOL = getLeftSideOnLane(lane) + lateralShift;
    2359              :                 const bool outsideLeft = leftOL > lane->getWidth();
    2360              : #ifdef DEBUG_PLAN_MOVE
    2361              :                 if (DEBUG_COND) {
    2362              :                     std::cout << SIMTIME << " veh=" << getID() << " lane=" << lane->getID() << " rightOL=" << rightOL << " leftOL=" << leftOL << "\n";
    2363              :                 }
    2364              : #endif
    2365    191833706 :                 if (rightOL < 0 || outsideLeft) {
    2366      1378012 :                     MSLeaderInfo outsideLeaders(lane->getWidth());
    2367              :                     // if ego is driving outside lane bounds we must consider
    2368              :                     // potential leaders that are also outside bounds
    2369              :                     int sublaneOffset = 0;
    2370      1378012 :                     if (outsideLeft) {
    2371       593526 :                         sublaneOffset = MIN2(-1, -(int)ceil((leftOL - lane->getWidth()) / MSGlobals::gLateralResolution));
    2372              :                     } else {
    2373       784486 :                         sublaneOffset = MAX2(1, (int)ceil(-rightOL / MSGlobals::gLateralResolution));
    2374              :                     }
    2375      1378012 :                     outsideLeaders.setSublaneOffset(sublaneOffset);
    2376              : #ifdef DEBUG_PLAN_MOVE
    2377              :                     if (DEBUG_COND) {
    2378              :                         std::cout << SIMTIME << " veh=" << getID() << " lane=" << lane->getID() << " sublaneOffset=" << sublaneOffset << " outsideLeft=" << outsideLeft << "\n";
    2379              :                     }
    2380              : #endif
    2381      5511563 :                     for (const MSVehicle* cand : lane->getVehiclesSecure()) {
    2382      1490766 :                         if ((lane != myLane || cand->getPositionOnLane() > getPositionOnLane())
    2383      4771770 :                                 && ((!outsideLeft && cand->getLeftSideOnEdge() < 0)
    2384      3280929 :                                     || (outsideLeft && cand->getLeftSideOnEdge() > lane->getEdge().getWidth()))) {
    2385        97454 :                             outsideLeaders.addLeader(cand, true);
    2386              : #ifdef DEBUG_PLAN_MOVE
    2387              :                             if (DEBUG_COND) {
    2388              :                                 std::cout << " outsideLeader=" << cand->getID() << " ahead=" << outsideLeaders.toString() << "\n";
    2389              :                             }
    2390              : #endif
    2391              :                         }
    2392              :                     }
    2393      1378012 :                     lane->releaseVehicles();
    2394      1378012 :                     if (outsideLeaders.hasVehicles()) {
    2395        26275 :                         adaptToLeaders(outsideLeaders, lateralShift, seen, lastLink, leaderLane, v, vLinkPass);
    2396              :                     }
    2397      1378012 :                 }
    2398              :             }
    2399   1151508216 :             adaptToLeaders(ahead, lateralShift, seen, lastLink, leaderLane, v, vLinkPass);
    2400              :         }
    2401   1151909368 :         if (lastLink != nullptr) {
    2402   1020364855 :             lastLink->myVLinkWait = MIN2(lastLink->myVLinkWait, v);
    2403              :         }
    2404              : #ifdef DEBUG_PLAN_MOVE
    2405              :         if (DEBUG_COND) {
    2406              :             std::cout << "\nv = " << v << "\n";
    2407              : 
    2408              :         }
    2409              : #endif
    2410              :         // XXX efficiently adapt to shadow leaders using neighAhead by iteration over the whole edge in parallel (lanechanger-style)
    2411   1151909368 :         if (myLaneChangeModel->getShadowLane() != nullptr) {
    2412              :             // also slow down for leaders on the shadowLane relative to the current lane
    2413      4852316 :             const MSLane* shadowLane = myLaneChangeModel->getShadowLane(leaderLane);
    2414              :             if (shadowLane != nullptr
    2415      4852316 :                     && (MSGlobals::gLateralResolution > 0 || getLateralOverlap() > POSITION_EPS
    2416              :                         // continous lane change cannot be stopped so we must adapt to the leader on the target lane
    2417       190992 :                         || myLaneChangeModel->getLaneChangeCompletion() < 0.5)) {
    2418      4328997 :                 if ((&shadowLane->getEdge() == &leaderLane->getEdge() || myLaneChangeModel->isOpposite())) {
    2419      4286678 :                     double latOffset = getLane()->getRightSideOnEdge() - myLaneChangeModel->getShadowLane()->getRightSideOnEdge();
    2420      4286678 :                     if (myLaneChangeModel->isOpposite()) {
    2421              :                         // ego posLat is added when retrieving sublanes but it
    2422              :                         // should be negated (subtract twice to compensate)
    2423       138571 :                         latOffset = ((myLane->getWidth() + shadowLane->getWidth()) * 0.5
    2424       138571 :                                      - 2 * getLateralPositionOnLane());
    2425              : 
    2426              :                     }
    2427      4286678 :                     MSLeaderInfo shadowLeaders = shadowLane->getLastVehicleInformation(this, latOffset, lane->getLength() - seen);
    2428              : #ifdef DEBUG_PLAN_MOVE
    2429              :                     if (DEBUG_COND && myLaneChangeModel->isOpposite()) {
    2430              :                         std::cout << SIMTIME << " opposite veh=" << getID() << " shadowLane=" << shadowLane->getID() << " latOffset=" << latOffset << " shadowLeaders=" << shadowLeaders.toString() << "\n";
    2431              :                     }
    2432              : #endif
    2433      4286678 :                     if (myLaneChangeModel->isOpposite()) {
    2434              :                         // ignore oncoming vehicles on the shadow lane
    2435       138571 :                         shadowLeaders.removeOpposite(shadowLane);
    2436              :                     }
    2437      4286678 :                     const double turningDifference = MAX2(0.0, leaderLane->getLength() - shadowLane->getLength());
    2438      4286678 :                     adaptToLeaders(shadowLeaders, latOffset, seen - turningDifference, lastLink, shadowLane, v, vLinkPass);
    2439      4328997 :                 } else if (shadowLane == myLaneChangeModel->getShadowLane() && leaderLane == myLane) {
    2440              :                     // check for leader vehicles driving in the opposite direction on the opposite-direction shadow lane
    2441              :                     // (and thus in the same direction as ego)
    2442        30455 :                     MSLeaderDistanceInfo shadowLeaders = shadowLane->getFollowersOnConsecutive(this, myLane->getOppositePos(getPositionOnLane()), true);
    2443              :                     const double latOffset = 0;
    2444              : #ifdef DEBUG_PLAN_MOVE
    2445              :                     if (DEBUG_COND) {
    2446              :                         std::cout << SIMTIME << " opposite shadows veh=" << getID() << " shadowLane=" << shadowLane->getID()
    2447              :                                   << " latOffset=" << latOffset << " shadowLeaders=" << shadowLeaders.toString() << "\n";
    2448              :                     }
    2449              : #endif
    2450        30455 :                     shadowLeaders.fixOppositeGaps(true);
    2451              : #ifdef DEBUG_PLAN_MOVE
    2452              :                     if (DEBUG_COND) {
    2453              :                         std::cout << "   shadowLeadersFixed=" << shadowLeaders.toString() << "\n";
    2454              :                     }
    2455              : #endif
    2456        30455 :                     adaptToLeaderDistance(shadowLeaders, latOffset, seen, lastLink, v, vLinkPass);
    2457        30455 :                 }
    2458              :             }
    2459              :         }
    2460              :         // adapt to pedestrians on the same lane
    2461   1151909368 :         if (lane->getEdge().getPersons().size() > 0 && lane->hasPedestrians()) {
    2462       193642 :             const double relativePos = lane->getLength() - seen;
    2463              : #ifdef DEBUG_PLAN_MOVE
    2464              :             if (DEBUG_COND) {
    2465              :                 std::cout << SIMTIME << " adapt to pedestrians on lane=" << lane->getID() << " relPos=" << relativePos << "\n";
    2466              :             }
    2467              : #endif
    2468       193642 :             const double stopTime = MAX2(1.0, ceil(getSpeed() / cfModel.getMaxDecel()));
    2469       193642 :             PersonDist leader = lane->nextBlocking(relativePos,
    2470       193642 :                                                    getRightSideOnLane(lane), getRightSideOnLane(lane) + getVehicleType().getWidth(), stopTime);
    2471       193642 :             if (leader.first != 0) {
    2472        20777 :                 const double stopSpeed = cfModel.stopSpeed(this, getSpeed(), leader.second - getVehicleType().getMinGap());
    2473        29431 :                 v = MIN2(v, stopSpeed);
    2474              : #ifdef DEBUG_PLAN_MOVE
    2475              :                 if (DEBUG_COND) {
    2476              :                     std::cout << SIMTIME << "    pedLeader=" << leader.first->getID() << " dist=" << leader.second << " v=" << v << "\n";
    2477              :                 }
    2478              : #endif
    2479              :             }
    2480              :         }
    2481   1151909368 :         if (lane->getBidiLane() != nullptr) {
    2482              :             // adapt to pedestrians on the bidi lane
    2483      3776920 :             const MSLane* bidiLane = lane->getBidiLane();
    2484      3776920 :             if (bidiLane->getEdge().getPersons().size() > 0 && bidiLane->hasPedestrians()) {
    2485         1028 :                 const double relativePos = seen;
    2486              : #ifdef DEBUG_PLAN_MOVE
    2487              :                 if (DEBUG_COND) {
    2488              :                     std::cout << SIMTIME << " adapt to pedestrians on lane=" << lane->getID() << " relPos=" << relativePos << "\n";
    2489              :                 }
    2490              : #endif
    2491         1028 :                 const double stopTime = ceil(getSpeed() / cfModel.getMaxDecel());
    2492         1028 :                 const double leftSideOnLane = bidiLane->getWidth() - getRightSideOnLane(lane);
    2493         1028 :                 PersonDist leader = bidiLane->nextBlocking(relativePos,
    2494         1028 :                                     leftSideOnLane - getVehicleType().getWidth(), leftSideOnLane, stopTime, true);
    2495         1028 :                 if (leader.first != 0) {
    2496          267 :                     const double stopSpeed = cfModel.stopSpeed(this, getSpeed(), leader.second - getVehicleType().getMinGap());
    2497          516 :                     v = MIN2(v, stopSpeed);
    2498              : #ifdef DEBUG_PLAN_MOVE
    2499              :                     if (DEBUG_COND) {
    2500              :                         std::cout << SIMTIME << "    pedLeader=" << leader.first->getID() << " dist=" << leader.second << " v=" << v << "\n";
    2501              :                     }
    2502              : #endif
    2503              :                 }
    2504              :             }
    2505              :         }
    2506              :         // adapt to vehicles blocked from (urgent) lane-changing
    2507   1151909368 :         if (!opposite && lane->getEdge().hasLaneChanger()) {
    2508    563727533 :             const double vHelp = myLaneChangeModel->getCooperativeHelpSpeed(lane, seen);
    2509              : #ifdef DEBUG_PLAN_MOVE
    2510              :             if (DEBUG_COND && vHelp < v) {
    2511              :                 std::cout << SIMTIME << "   applying cooperativeHelpSpeed v=" << vHelp << "\n";
    2512              :             }
    2513              : #endif
    2514    563765439 :             v = MIN2(v, vHelp);
    2515              :         }
    2516              : 
    2517              :         // process all stops and waypoints on the current edge
    2518              :         bool foundRealStop = false;
    2519              :         while (stopIt != myStops.end()
    2520     55454747 :                 && ((&stopIt->lane->getEdge() == &lane->getEdge())
    2521     26452460 :                     || (stopIt->isOpposite && stopIt->lane->getEdge().getOppositeEdge() == &lane->getEdge()))
    2522              :                 // ignore stops that occur later in a looped route
    2523   1200052134 :                 && stopIt->edge == myCurrEdge + view) {
    2524     28955933 :             double stopDist = std::numeric_limits<double>::max();
    2525              :             const MSStop& stop = *stopIt;
    2526              :             const bool isFirstStop = stopIt == myStops.begin();
    2527              :             stopIt++;
    2528     28955933 :             if (!stop.reached || (stop.getSpeed() > 0 && keepStopping())) {
    2529              :                 // we are approaching a stop on the edge; must not drive further
    2530     11123251 :                 bool isWaypoint = stop.getSpeed() > 0;
    2531     11123251 :                 double endPos = stop.getEndPos(*this) + NUMERICAL_EPS;
    2532     11123251 :                 if (stop.parkingarea != nullptr) {
    2533              :                     // leave enough space so parking vehicles can exit
    2534      1568054 :                     const double brakePos = getBrakeGap() + lane->getLength() - seen;
    2535      1568054 :                     endPos = stop.parkingarea->getLastFreePosWithReservation(t, *this, brakePos);
    2536      9555197 :                 } else if (isWaypoint && !stop.reached) {
    2537       101979 :                     endPos = stop.pars.startPos;
    2538              :                 }
    2539     11123251 :                 stopDist = seen + endPos - lane->getLength();
    2540              : #ifdef DEBUG_STOPS
    2541              :                 if (DEBUG_COND) {
    2542              :                     std::cout << SIMTIME << " veh=" << getID() <<  " stopDist=" << stopDist << " stopLane=" << stop.lane->getID() << " stopEndPos=" << endPos << "\n";
    2543              :                 }
    2544              : #endif
    2545              :                 // regular stops are not emergencies
    2546              :                 double stopSpeed = laneMaxV;
    2547     11123251 :                 if (isWaypoint) {
    2548              :                     bool waypointWithStop = false;
    2549       117486 :                     if (stop.getUntil() > t) {
    2550              :                         // check if we have to slow down or even stop
    2551              :                         SUMOTime time2end = 0;
    2552         4051 :                         if (stop.reached) {
    2553          800 :                             time2end = TIME2STEPS((stop.pars.endPos - myState.myPos) / stop.getSpeed());
    2554              :                         } else {
    2555         3437 :                             time2end = TIME2STEPS(
    2556              :                                            // time to reach waypoint start
    2557              :                                            stopDist / ((getSpeed() + stop.getSpeed()) / 2)
    2558              :                                            // time to reach waypoint end
    2559              :                                            + (stop.pars.endPos - stop.pars.startPos) / stop.getSpeed());
    2560              :                         }
    2561         4051 :                         if (stop.getUntil() > t + time2end) {
    2562              :                             // we need to stop
    2563              :                             double distToEnd = stopDist;
    2564         3915 :                             if (!stop.reached) {
    2565         3191 :                                 distToEnd += stop.pars.endPos - stop.pars.startPos;
    2566              :                             }
    2567         3915 :                             stopSpeed = MAX2(cfModel.stopSpeed(this, getSpeed(), distToEnd), vMinComfortable);
    2568              :                             waypointWithStop = true;
    2569              :                         }
    2570              :                     }
    2571       117486 :                     if (stop.reached) {
    2572        14754 :                         stopSpeed = MIN2(stop.getSpeed(), stopSpeed);
    2573        14754 :                         if (myState.myPos >= stop.pars.endPos && !waypointWithStop) {
    2574          263 :                             stopDist = std::numeric_limits<double>::max();
    2575              :                         }
    2576              :                     } else {
    2577       102732 :                         stopSpeed = MIN2(MAX2(cfModel.freeSpeed(this, getSpeed(), stopDist, stop.getSpeed()), vMinComfortable), stopSpeed);
    2578       102732 :                         if (!stop.reached) {
    2579       102732 :                             stopDist += stop.pars.endPos - stop.pars.startPos;
    2580              :                         }
    2581       102732 :                         if (lastLink != nullptr) {
    2582        64827 :                             lastLink->adaptLeaveSpeed(cfModel.freeSpeed(this, vLinkPass, endPos, stop.getSpeed(), false, MSCFModel::CalcReason::FUTURE));
    2583              :                         }
    2584              :                     }
    2585              :                 } else {
    2586     11005765 :                     stopSpeed = MAX2(cfModel.stopSpeed(this, getSpeed(), stopDist), vMinComfortable);
    2587     11005765 :                     if (lastLink != nullptr) {
    2588      4728605 :                         lastLink->adaptLeaveSpeed(cfModel.stopSpeed(this, vLinkPass, endPos, MSCFModel::CalcReason::FUTURE));
    2589              :                     }
    2590              :                 }
    2591     11123251 :                 v = MIN2(v, stopSpeed);
    2592     11123251 :                 if (lane->isInternal()) {
    2593         6703 :                     std::vector<MSLink*>::const_iterator exitLink = MSLane::succLinkSec(*this, view + 1, *lane, bestLaneConts);
    2594              :                     assert(!lane->isLinkEnd(exitLink));
    2595              :                     bool dummySetRequest;
    2596              :                     double dummyVLinkWait;
    2597         6703 :                     checkLinkLeaderCurrentAndParallel(*exitLink, lane, seen, lastLink, v, vLinkPass, dummyVLinkWait, dummySetRequest);
    2598              :                 }
    2599              : 
    2600              : #ifdef DEBUG_PLAN_MOVE
    2601              :                 if (DEBUG_COND) {
    2602              :                     std::cout << "\n" << SIMTIME << " next stop: distance = " << stopDist << " requires stopSpeed = " << stopSpeed << "\n";
    2603              : 
    2604              :                 }
    2605              : #endif
    2606     11123251 :                 if (isFirstStop) {
    2607     10204639 :                     newStopDist = stopDist;
    2608              :                     // if the vehicle is going to stop we don't need to look further
    2609              :                     // (except for trains that make use of further link-approach registration for safety purposes)
    2610     10204639 :                     if (!isWaypoint) {
    2611              :                         planningToStop = true;
    2612     10121730 :                         if (!isRail()) {
    2613      9818615 :                             lfLinks.emplace_back(v, stopDist);
    2614              :                             foundRealStop = true;
    2615      9818615 :                             break;
    2616              :                         }
    2617              :                     }
    2618              :                 }
    2619              :             }
    2620              :         }
    2621              :         if (foundRealStop) {
    2622              :             break;
    2623              :         }
    2624              : 
    2625              :         // move to next lane
    2626              :         //  get the next link used
    2627   1142090753 :         std::vector<MSLink*>::const_iterator link = MSLane::succLinkSec(*this, view + 1, *lane, bestLaneConts);
    2628   1142090753 :         if (lane->isLinkEnd(link) && myLaneChangeModel->hasBlueLight() && myCurrEdge != myRoute->end() - 1) {
    2629              :             // emergency vehicle is on the wrong lane. Obtain the link that it would use from the correct turning lane
    2630              :             const int currentIndex = lane->getIndex();
    2631              :             const MSLane* bestJump = nullptr;
    2632       194441 :             for (const LaneQ& preb : getBestLanes()) {
    2633       127880 :                 if (preb.allowsContinuation &&
    2634              :                         (bestJump == nullptr
    2635         3212 :                          || abs(currentIndex - preb.lane->getIndex()) < abs(currentIndex - bestJump->getIndex()))) {
    2636        67566 :                     bestJump = preb.lane;
    2637              :                 }
    2638              :             }
    2639        66561 :             if (bestJump != nullptr) {
    2640        66561 :                 const MSEdge* nextEdge = *(myCurrEdge + 1);
    2641       122907 :                 for (auto cand_it = bestJump->getLinkCont().begin(); cand_it != bestJump->getLinkCont().end(); cand_it++) {
    2642       117526 :                     if (&(*cand_it)->getLane()->getEdge() == nextEdge) {
    2643              :                         link = cand_it;
    2644              :                         break;
    2645              :                     }
    2646              :                 }
    2647              :             }
    2648              :         }
    2649              : 
    2650              :         // Check whether this is a turn (to save info about the next upcoming turn)
    2651   1142090753 :         if (!encounteredTurn) {
    2652    185984031 :             if (!lane->isLinkEnd(link) && lane->getLinkCont().size() > 1) {
    2653     18471665 :                 LinkDirection linkDir = (*link)->getDirection();
    2654     18471665 :                 switch (linkDir) {
    2655              :                     case LinkDirection::STRAIGHT:
    2656              :                     case LinkDirection::NODIR:
    2657              :                         break;
    2658      6807564 :                     default:
    2659      6807564 :                         nextTurn.first = seen;
    2660      6807564 :                         nextTurn.second = *link;
    2661              :                         encounteredTurn = true;
    2662              : #ifdef DEBUG_NEXT_TURN
    2663              :                         if (DEBUG_COND) {
    2664              :                             std::cout << SIMTIME << " veh '" << getID() << "' nextTurn: " << toString(linkDir)
    2665              :                                       << " at " << nextTurn.first << "m." << std::endl;
    2666              :                         }
    2667              : #endif
    2668              :                 }
    2669              :             }
    2670              :         }
    2671              : 
    2672              :         //  check whether the vehicle is on its final edge
    2673   1964335168 :         if (myCurrEdge + view + 1 == myRoute->end()
    2674   1142090753 :                 || (myParameter->arrivalEdge >= 0 && getRoutePosition() + view == myParameter->arrivalEdge)) {
    2675    319846338 :             const double arrivalSpeed = (myParameter->arrivalSpeedProcedure == ArrivalSpeedDefinition::GIVEN ?
    2676              :                                          myParameter->arrivalSpeed : laneMaxV);
    2677              :             // subtract the arrival speed from the remaining distance so we get one additional driving step with arrival speed
    2678              :             // XXX: This does not work for ballistic update refs #2579
    2679    319846338 :             const double distToArrival = seen + myArrivalPos - lane->getLength() - SPEED2DIST(arrivalSpeed);
    2680    319846338 :             const double va = MAX2(NUMERICAL_EPS, cfModel.freeSpeed(this, getSpeed(), distToArrival, arrivalSpeed));
    2681    319846338 :             v = MIN2(v, va);
    2682    319846338 :             if (lastLink != nullptr) {
    2683              :                 lastLink->adaptLeaveSpeed(va);
    2684              :             }
    2685    319846338 :             lfLinks.push_back(DriveProcessItem(v, seen, lane->getEdge().isFringe() ? 1000 : 0));
    2686    319846338 :             break;
    2687              :         }
    2688              :         // check whether the lane or the shadowLane is a dead end (allow some leeway on intersections)
    2689              :         if (lane->isLinkEnd(link)
    2690    809514415 :                 || (MSGlobals::gSublane && brakeForOverlap(*link, lane))
    2691   1631404971 :                 || (opposite && (*link)->getViaLaneOrLane()->getParallelOpposite() == nullptr
    2692       212757 :                     && !myLaneChangeModel->hasBlueLight())) {
    2693     13335082 :             double va = cfModel.stopSpeed(this, getSpeed(), seen);
    2694     13335082 :             if (lastLink != nullptr) {
    2695              :                 lastLink->adaptLeaveSpeed(va);
    2696              :             }
    2697     13335082 :             if (myLaneChangeModel->getCommittedSpeed() > 0) {
    2698       338411 :                 v = MIN2(myLaneChangeModel->getCommittedSpeed(), v);
    2699              :             } else {
    2700     25441929 :                 v = MIN2(va, v);
    2701              :             }
    2702              : #ifdef DEBUG_PLAN_MOVE
    2703              :             if (DEBUG_COND) {
    2704              :                 std::cout << "   braking for link end lane=" << lane->getID() << " seen=" << seen
    2705              :                           << " overlap=" << getLateralOverlap() << " va=" << va << " committed=" << myLaneChangeModel->getCommittedSpeed() << " v=" << v << "\n";
    2706              : 
    2707              :             }
    2708              : #endif
    2709     13335082 :             if (lane->isLinkEnd(link)) {
    2710     12730000 :                 lfLinks.emplace_back(v, seen);
    2711              :                 break;
    2712              :             }
    2713              :         }
    2714    809514415 :         lateralShift += (*link)->getLateralShift();
    2715    809514415 :         const bool yellowOrRed = (*link)->haveRed() || (*link)->haveYellow();
    2716              :         // We distinguish 3 cases when determining the point at which a vehicle stops:
    2717              :         // - allway_stop: the vehicle should stop close to the stop line but may stop at larger distance
    2718              :         // - red/yellow light: here the vehicle 'knows' that it will have priority eventually and does not need to stop on a precise spot
    2719              :         // - other types of minor links: the vehicle needs to stop as close to the junction as necessary
    2720              :         //   to minimize the time window for passing the junction. If the
    2721              :         //   vehicle 'decides' to accelerate and cannot enter the junction in
    2722              :         //   the next step, new foes may appear and cause a collision (see #1096)
    2723              :         // - major links: stopping point is irrelevant
    2724              :         double laneStopOffset;
    2725    809514415 :         const double majorStopOffset = MAX2(getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_GAP, DIST_TO_STOPLINE_EXPECT_PRIORITY), lane->getVehicleStopOffset(this));
    2726              :         // override low desired decel at yellow and red
    2727    809514415 :         const double stopDecel = yellowOrRed && !isRail() ? MAX2(MIN2(MSGlobals::gTLSYellowMinDecel, cfModel.getEmergencyDecel()), cfModel.getMaxDecel()) : cfModel.getMaxDecel();
    2728    809514415 :         const double brakeDist = cfModel.brakeGap(myState.mySpeed, stopDecel, 0);
    2729    809514415 :         const bool canBrakeBeforeLaneEnd = seen >= brakeDist;
    2730    809514415 :         const bool canBrakeBeforeStopLine = seen - lane->getVehicleStopOffset(this) >= brakeDist;
    2731    809514415 :         if (yellowOrRed) {
    2732              :             // Wait at red traffic light with full distance if possible
    2733              :             laneStopOffset = majorStopOffset;
    2734    754270168 :         } else if ((*link)->havePriority()) {
    2735              :             // On priority link, we should never stop below visibility distance
    2736    714767178 :             laneStopOffset = MIN2((*link)->getFoeVisibilityDistance() - POSITION_EPS, majorStopOffset);
    2737              :         } else {
    2738     39502990 :             double minorStopOffset = MAX2(lane->getVehicleStopOffset(this),
    2739     39502990 :                                           getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_CROSSING_GAP, MSPModel::SAFETY_GAP) - (*link)->getDistToFoePedCrossing());
    2740              : #ifdef DEBUG_PLAN_MOVE
    2741              :             if (DEBUG_COND) {
    2742              :                 std::cout << "  minorStopOffset=" << minorStopOffset << " distToFoePedCrossing=" << (*link)->getDistToFoePedCrossing() << "\n";
    2743              :             }
    2744              : #endif
    2745     39502990 :             if ((*link)->getState() == LINKSTATE_ALLWAY_STOP) {
    2746      1361478 :                 minorStopOffset = MAX2(minorStopOffset, getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_GAP, 0));
    2747              :             } else {
    2748     38141512 :                 minorStopOffset = MAX2(minorStopOffset, getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_GAP_MINOR, 0));
    2749              :             }
    2750              :             // On minor link, we should likewise never stop below visibility distance
    2751     39502990 :             laneStopOffset = MIN2((*link)->getFoeVisibilityDistance() - POSITION_EPS, minorStopOffset);
    2752              :         }
    2753              : #ifdef DEBUG_PLAN_MOVE
    2754              :         if (DEBUG_COND) {
    2755              :             std::cout << SIMTIME << " veh=" << getID() << " desired stopOffset on lane '" << lane->getID() << "' is " << laneStopOffset << "\n";
    2756              :         }
    2757              : #endif
    2758    809514415 :         if (canBrakeBeforeLaneEnd) {
    2759              :             // avoid emergency braking if possible
    2760    782663112 :             laneStopOffset = MIN2(laneStopOffset, seen - brakeDist);
    2761              :         }
    2762              :         laneStopOffset = MAX2(POSITION_EPS, laneStopOffset);
    2763    809514415 :         double stopDist = MAX2(0., seen - laneStopOffset);
    2764     55244247 :         if (yellowOrRed && getDevice(typeid(MSDevice_GLOSA)) != nullptr
    2765          508 :                 && static_cast<MSDevice_GLOSA*>(getDevice(typeid(MSDevice_GLOSA)))->getOverrideSafety()
    2766    809514415 :                 && static_cast<MSDevice_GLOSA*>(getDevice(typeid(MSDevice_GLOSA)))->isSpeedAdviceActive()) {
    2767              :             stopDist = std::numeric_limits<double>::max();
    2768              :         }
    2769    809514415 :         if (newStopDist != std::numeric_limits<double>::max()) {
    2770              :             stopDist = MAX2(stopDist, newStopDist);
    2771              :         }
    2772              : #ifdef DEBUG_PLAN_MOVE
    2773              :         if (DEBUG_COND) {
    2774              :             std::cout << SIMTIME << " veh=" << getID() << " effective stopOffset on lane '" << lane->getID()
    2775              :                       << "' is " << laneStopOffset << " (-> stopDist=" << stopDist << ")" << std::endl;
    2776              :         }
    2777              : #endif
    2778    809514415 :         if (isRail()
    2779    809514415 :                 && !lane->isInternal()) {
    2780              :             // check for train direction reversal
    2781      2945513 :             if (lane->getBidiLane() != nullptr
    2782      2945513 :                     && (*link)->getLane()->getBidiLane() == lane) {
    2783       629988 :                 double vMustReverse = getCarFollowModel().stopSpeed(this, getSpeed(), seen - POSITION_EPS);
    2784       629988 :                 if (seen < 1) {
    2785         2261 :                     mustSeeBeforeReversal = 2 * seen + getLength();
    2786              :                 }
    2787      1219331 :                 v = MIN2(v, vMustReverse);
    2788              :             }
    2789              :             // signal that is passed in the current step does not count
    2790      5891026 :             foundRailSignal |= ((*link)->getTLLogic() != nullptr
    2791       639663 :                                 && (*link)->getTLLogic()->getLogicType() == TrafficLightType::RAIL_SIGNAL
    2792      3495983 :                                 && seen > SPEED2DIST(v));
    2793              :         }
    2794              : 
    2795    809514415 :         bool canReverseEventually = false;
    2796    809514415 :         const double vReverse = checkReversal(canReverseEventually, laneMaxV, seen);
    2797    809514415 :         v = MIN2(v, vReverse);
    2798              : #ifdef DEBUG_PLAN_MOVE
    2799              :         if (DEBUG_COND) {
    2800              :             std::cout << SIMTIME << " veh=" << getID() << " canReverseEventually=" << canReverseEventually << " v=" << v << "\n";
    2801              :         }
    2802              : #endif
    2803              : 
    2804              :         // check whether we need to slow down in order to finish a continuous lane change
    2805    809514415 :         if (myLaneChangeModel->isChangingLanes()) {
    2806              :             if (    // slow down to finish lane change before a turn lane
    2807       160591 :                 ((*link)->getDirection() == LinkDirection::LEFT || (*link)->getDirection() == LinkDirection::RIGHT) ||
    2808              :                 // slow down to finish lane change before the shadow lane ends
    2809       137201 :                 (myLaneChangeModel->getShadowLane() != nullptr &&
    2810       137201 :                  (*link)->getViaLaneOrLane()->getParallelLane(myLaneChangeModel->getShadowDirection()) == nullptr)) {
    2811              :                 // XXX maybe this is too harsh. Vehicles could cut some corners here
    2812        46405 :                 const double timeRemaining = STEPS2TIME(myLaneChangeModel->remainingTime());
    2813              :                 assert(timeRemaining != 0);
    2814              :                 // XXX: Euler-logic (#860), but I couldn't identify problems from this yet (Leo). Refs. #2575
    2815        46405 :                 const double va = MAX2(cfModel.stopSpeed(this, getSpeed(), seen - POSITION_EPS),
    2816        46405 :                                        (seen - POSITION_EPS) / timeRemaining);
    2817              : #ifdef DEBUG_PLAN_MOVE
    2818              :                 if (DEBUG_COND) {
    2819              :                     std::cout << SIMTIME << " veh=" << getID() << " slowing down to finish continuous change before"
    2820              :                               << " link=" << (*link)->getViaLaneOrLane()->getID()
    2821              :                               << " timeRemaining=" << timeRemaining
    2822              :                               << " v=" << v
    2823              :                               << " va=" << va
    2824              :                               << std::endl;
    2825              :                 }
    2826              : #endif
    2827        92609 :                 v = MIN2(va, v);
    2828              :             }
    2829              :         }
    2830              : 
    2831              :         // - always issue a request to leave the intersection we are currently on
    2832    809514415 :         const bool leavingCurrentIntersection = myLane->getEdge().isInternal() && lastLink == nullptr;
    2833              :         // - do not issue a request to enter an intersection after we already slowed down for an earlier one
    2834    809514415 :         const bool abortRequestAfterMinor = slowedDownForMinor && (*link)->getInternalLaneBefore() == nullptr;
    2835              :         // - even if red, if we cannot break we should issue a request
    2836    809514415 :         bool setRequest = (v > NUMERICAL_EPS_SPEED && !abortRequestAfterMinor) || (leavingCurrentIntersection);
    2837              : 
    2838    809514415 :         double stopSpeed = cfModel.stopSpeed(this, getSpeed(), stopDist, stopDecel, MSCFModel::CalcReason::CURRENT_WAIT);
    2839    809514415 :         double vLinkWait = MIN2(v, stopSpeed);
    2840              : #ifdef DEBUG_PLAN_MOVE
    2841              :         if (DEBUG_COND) {
    2842              :             std::cout
    2843              :                     << " stopDist=" << stopDist
    2844              :                     << " stopDecel=" << stopDecel
    2845              :                     << " vLinkWait=" << vLinkWait
    2846              :                     << " brakeDist=" << brakeDist
    2847              :                     << " seen=" << seen
    2848              :                     << " leaveIntersection=" << leavingCurrentIntersection
    2849              :                     << " setRequest=" << setRequest
    2850              :                     //<< std::setprecision(16)
    2851              :                     //<< " v=" << v
    2852              :                     //<< " speedEps=" << NUMERICAL_EPS_SPEED
    2853              :                     //<< std::setprecision(gPrecision)
    2854              :                     << "\n";
    2855              :         }
    2856              : #endif
    2857              : 
    2858    809514415 :         if (yellowOrRed && canBrakeBeforeStopLine && !ignoreRed(*link, canBrakeBeforeStopLine) && seen >= mustSeeBeforeReversal) {
    2859     55184676 :             if (lane->isInternal()) {
    2860        42351 :                 checkLinkLeaderCurrentAndParallel(*link, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest);
    2861              :             }
    2862              :             // arrivalSpeed / arrivalTime when braking for red light is only relevent for rail signal switching
    2863     55184676 :             const SUMOTime arrivalTime = getArrivalTime(t, seen, v, vLinkPass);
    2864              :             // the vehicle is able to brake in front of a yellow/red traffic light
    2865     55184676 :             lfLinks.push_back(DriveProcessItem(*link, v, vLinkWait, false, arrivalTime, vLinkWait, 0, seen, -1));
    2866              :             //lfLinks.push_back(DriveProcessItem(0, vLinkWait, vLinkWait, false, 0, 0, stopDist));
    2867     55184676 :             break;
    2868              :         }
    2869              : 
    2870    754329739 :         const MSLink* entryLink = (*link)->getCorrespondingEntryLink();
    2871    754329739 :         if (entryLink->haveRed() && ignoreRed(*link, canBrakeBeforeStopLine) && STEPS2TIME(t - entryLink->getLastStateChange()) > 2) {
    2872              :             // restrict speed when ignoring a red light
    2873       118508 :             const double redSpeed = MIN2(v, getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_DRIVE_RED_SPEED, v));
    2874       118508 :             const double va = MAX2(redSpeed, cfModel.freeSpeed(this, getSpeed(), seen, redSpeed));
    2875       236567 :             v = MIN2(va, v);
    2876              : #ifdef DEBUG_PLAN_MOVE
    2877              :             if (DEBUG_COND) std::cout
    2878              :                         << "   ignoreRed spent=" << STEPS2TIME(t - (*link)->getLastStateChange())
    2879              :                         << " redSpeed=" << redSpeed
    2880              :                         << " va=" << va
    2881              :                         << " v=" << v
    2882              :                         << "\n";
    2883              : #endif
    2884              :         }
    2885              : 
    2886    754329739 :         checkLinkLeaderCurrentAndParallel(*link, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest);
    2887              : 
    2888    754329739 :         if (lastLink != nullptr) {
    2889              :             lastLink->adaptLeaveSpeed(laneMaxV);
    2890              :         }
    2891    754329739 :         double arrivalSpeed = vLinkPass;
    2892              :         // vehicles should decelerate when approaching a minor link
    2893              :         // - unless they are close enough to have clear visibility of all relevant foe lanes and may start to accelerate again
    2894              :         // - and unless they are so close that stopping is impossible (i.e. when a green light turns to yellow when close to the junction)
    2895              : 
    2896              :         // whether the vehicle/driver is close enough to the link to see all possible foes #2123
    2897    754329739 :         const double visibilityDistance = (*link)->getFoeVisibilityDistance();
    2898    754329739 :         const double determinedFoePresence = seen <= visibilityDistance;
    2899              : //        // VARIANT: account for time needed to recognize whether relevant vehicles are on the foe lanes. (Leo)
    2900              : //        double foeRecognitionTime = 0.0;
    2901              : //        double determinedFoePresence = seen < visibilityDistance - myState.mySpeed*foeRecognitionTime;
    2902              : 
    2903              : #ifdef DEBUG_PLAN_MOVE
    2904              :         if (DEBUG_COND) {
    2905              :             std::cout << " approaching link=" << (*link)->getViaLaneOrLane()->getID() << " prio=" << (*link)->havePriority() << " seen=" << seen << " visibilityDistance=" << visibilityDistance << " brakeDist=" << brakeDist << "\n";
    2906              :         }
    2907              : #endif
    2908              : 
    2909    754329739 :         const bool couldBrakeForMinor = !(*link)->havePriority() && brakeDist < seen && !(*link)->lastWasContMajor();
    2910     39036802 :         if (couldBrakeForMinor && !determinedFoePresence) {
    2911              :             // vehicle decelerates just enough to be able to stop if necessary and then accelerates
    2912     36428936 :             double maxSpeedAtVisibilityDist = cfModel.maximumSafeStopSpeed(visibilityDistance, cfModel.getMaxDecel(), myState.mySpeed, false, 0., false);
    2913              :             // XXX: estimateSpeedAfterDistance does not use euler-logic (thus returns a lower value than possible here...)
    2914     36428936 :             double maxArrivalSpeed = cfModel.estimateSpeedAfterDistance(visibilityDistance, maxSpeedAtVisibilityDist, cfModel.getMaxAccel());
    2915     36428936 :             arrivalSpeed = MIN2(vLinkPass, maxArrivalSpeed);
    2916              :             slowedDownForMinor = true;
    2917              : #ifdef DEBUG_PLAN_MOVE
    2918              :             if (DEBUG_COND) {
    2919              :                 std::cout << "   slowedDownForMinor maxSpeedAtVisDist=" << maxSpeedAtVisibilityDist << " maxArrivalSpeed=" << maxArrivalSpeed << " arrivalSpeed=" << arrivalSpeed << "\n";
    2920              :             }
    2921              : #endif
    2922    717900803 :         } else if ((*link)->getState() == LINKSTATE_EQUAL && myWaitingTime > 0) {
    2923              :             // check for deadlock (circular yielding)
    2924              :             //std::cout << SIMTIME << " veh=" << getID() << " check rbl-deadlock\n";
    2925         2938 :             std::pair<const SUMOVehicle*, const MSLink*> blocker = (*link)->getFirstApproachingFoe(*link);
    2926              :             //std::cout << "   blocker=" << Named::getIDSecure(blocker.first) << "\n";
    2927              :             int n = 100;
    2928         5756 :             while (blocker.second != nullptr && blocker.second != *link && n > 0) {
    2929         2818 :                 blocker = blocker.second->getFirstApproachingFoe(*link);
    2930         2818 :                 n--;
    2931              :                 //std::cout << "   blocker=" << Named::getIDSecure(blocker.first) << "\n";
    2932              :             }
    2933         2938 :             if (n == 0) {
    2934            0 :                 WRITE_WARNINGF(TL("Suspicious right_before_left junction '%'."), lane->getEdge().getToJunction()->getID());
    2935              :             }
    2936              :             //std::cout << "   blockerLink=" << blocker.second << " link=" << *link << "\n";
    2937         2938 :             if (blocker.second == *link) {
    2938          488 :                 const double threshold = (*link)->getDirection() == LinkDirection::STRAIGHT ? 0.25 : 0.75;
    2939          488 :                 if (RandHelper::rand(getRNG()) < threshold) {
    2940              :                     //std::cout << "   abort request, threshold=" << threshold << "\n";
    2941          310 :                     setRequest = false;
    2942              :                 }
    2943              :             }
    2944              :         }
    2945              : 
    2946    754329739 :         const SUMOTime arrivalTime = getArrivalTime(t, seen, v, arrivalSpeed);
    2947    754329739 :         if (couldBrakeForMinor && determinedFoePresence && (*link)->getLane()->getEdge().isRoundabout()) {
    2948       876681 :             const bool wasOpened = (*link)->opened(arrivalTime, arrivalSpeed, arrivalSpeed,
    2949       876681 :                                                    getLength(), getImpatience(),
    2950              :                                                    getCarFollowModel().getMaxDecel(),
    2951       876681 :                                                    getWaitingTime(), getLateralPositionOnLane(),
    2952              :                                                    nullptr, false, this);
    2953       876681 :             if (!wasOpened) {
    2954              :                 slowedDownForMinor = true;
    2955              :             }
    2956              : #ifdef DEBUG_PLAN_MOVE
    2957              :             if (DEBUG_COND) {
    2958              :                 std::cout << "   slowedDownForMinor at roundabout=" << (!wasOpened) << "\n";
    2959              :             }
    2960              : #endif
    2961              :         }
    2962              : 
    2963              :         // compute arrival speed and arrival time if vehicle starts braking now
    2964              :         // if stopping is possible, arrivalTime can be arbitrarily large. A small value keeps fractional times (impatience) meaningful
    2965              :         double arrivalSpeedBraking = 0;
    2966    754329739 :         const double bGap = cfModel.brakeGap(v);
    2967    754329739 :         if (seen < bGap && !isStopped() && !planningToStop) { // XXX: should this use the current speed (at least for the ballistic case)? (Leo) Refs. #2575
    2968              :             // vehicle cannot come to a complete stop in time
    2969     53568240 :             if (MSGlobals::gSemiImplicitEulerUpdate) {
    2970     50909104 :                 arrivalSpeedBraking = cfModel.getMinimalArrivalSpeedEuler(seen, v);
    2971              :                 // due to discrete/continuous mismatch (when using Euler update) we have to ensure that braking actually helps
    2972              :                 arrivalSpeedBraking = MIN2(arrivalSpeedBraking, arrivalSpeed);
    2973              :             } else {
    2974      2659136 :                 arrivalSpeedBraking = cfModel.getMinimalArrivalSpeed(seen, myState.mySpeed);
    2975              :             }
    2976              :         }
    2977              : 
    2978              :         // estimate leave speed for passing time computation
    2979              :         // l=linkLength, a=accel, t=continuousTime, v=vLeave
    2980              :         // l=v*t + 0.5*a*t^2, solve for t and multiply with a, then add v
    2981   1120896591 :         const double estimatedLeaveSpeed = MIN2((*link)->getViaLaneOrLane()->getVehicleMaxSpeed(this, maxVD),
    2982    754329739 :                                                 getCarFollowModel().estimateSpeedAfterDistance((*link)->getLength(), arrivalSpeed, getVehicleType().getCarFollowModel().getMaxAccel()));
    2983    754329739 :         lfLinks.push_back(DriveProcessItem(*link, v, vLinkWait, setRequest,
    2984              :                                            arrivalTime, arrivalSpeed,
    2985              :                                            arrivalSpeedBraking,
    2986              :                                            seen, estimatedLeaveSpeed));
    2987    754329739 :         if ((*link)->getViaLane() == nullptr) {
    2988              :             hadNonInternal = true;
    2989              :             ++view;
    2990              :         }
    2991              : #ifdef DEBUG_PLAN_MOVE
    2992              :         if (DEBUG_COND) {
    2993              :             std::cout << "   checkAbort setRequest=" << setRequest << " v=" << v << " seen=" << seen << " dist=" << dist
    2994              :                       << " seenNonInternal=" << seenNonInternal
    2995              :                       << " seenInternal=" << seenInternal << " length=" << vehicleLength << "\n";
    2996              :         }
    2997              : #endif
    2998              :         // we need to look ahead far enough to see available space for checkRewindLinkLanes
    2999    778383053 :         if ((!setRequest || v <= 0 || seen > dist) && hadNonInternal && seenNonInternal > MAX2(vehicleLength * CRLL_LOOK_AHEAD, vehicleLength + seenInternal) && foundRailSignal) {
    3000              :             break;
    3001              :         }
    3002              :         // get the following lane
    3003              :         lane = (*link)->getViaLaneOrLane();
    3004    543524651 :         laneMaxV = lane->getVehicleMaxSpeed(this, maxVD);
    3005    543925328 :         if (myInfluencer && !myInfluencer->considerSpeedLimit()) {
    3006              :             laneMaxV = std::numeric_limits<double>::max();
    3007              :         }
    3008              :         // the link was passed
    3009              :         // compute the velocity to use when the link is not blocked by other vehicles
    3010              :         //  the vehicle shall be not faster when reaching the next lane than allowed
    3011              :         //  speed limits are not emergencies (e.g. when the limit changes suddenly due to TraCI or a variableSpeedSignal)
    3012    543524651 :         const double va = MAX2(cfModel.freeSpeed(this, getSpeed(), seen, laneMaxV), vMinComfortable);
    3013   1077737857 :         v = MIN2(va, v);
    3014              : #ifdef DEBUG_PLAN_MOVE
    3015              :         if (DEBUG_COND) {
    3016              :             std::cout << "   laneMaxV=" << laneMaxV << " freeSpeed=" << va << " v=" << v << "\n";
    3017              :         }
    3018              : #endif
    3019    543524651 :         if (lane->getEdge().isInternal()) {
    3020    234791389 :             seenInternal += lane->getLength();
    3021              :         } else {
    3022    308733262 :             seenNonInternal += lane->getLength();
    3023              :         }
    3024              :         // do not restrict results to the current vehicle to allow caching for the current time step
    3025    543524651 :         leaderLane = opposite ? lane->getParallelOpposite() : lane;
    3026    543524651 :         if (leaderLane == nullptr) {
    3027              : 
    3028              :             break;
    3029              :         }
    3030   1086627766 :         ahead = opposite ? MSLeaderInfo(leaderLane->getWidth()) : leaderLane->getLastVehicleInformation(nullptr, 0);
    3031    543313883 :         seen += lane->getLength();
    3032   1086627766 :         vLinkPass = MIN2(cfModel.estimateSpeedAfterDistance(lane->getLength(), v, cfModel.getMaxAccel()), laneMaxV); // upper bound
    3033              :         lastLink = &lfLinks.back();
    3034    543313883 :     }
    3035              : 
    3036              : //#ifdef DEBUG_PLAN_MOVE
    3037              : //    if(DEBUG_COND){
    3038              : //        std::cout << "planMoveInternal found safe speed v = " << v << std::endl;
    3039              : //    }
    3040              : //#endif
    3041              : 
    3042              : #ifdef PARALLEL_STOPWATCH
    3043              :     myLane->getStopWatch()[0].stop();
    3044              : #endif
    3045    608595485 : }
    3046              : 
    3047              : 
    3048              : double
    3049         2786 : MSVehicle::slowDownForSchedule(double vMinComfortable) const {
    3050         2786 :     const double sfp = getVehicleType().getParameter().speedFactorPremature;
    3051              :     const MSStop& stop = myStops.front();
    3052         2786 :     std::pair<double, double> timeDist = estimateTimeToNextStop();
    3053         2786 :     double arrivalDelay = SIMTIME + timeDist.first - STEPS2TIME(stop.pars.arrival);
    3054         2786 :     double t = STEPS2TIME(stop.pars.arrival - SIMSTEP);
    3055         5572 :     if (stop.pars.hasParameter(toString(SUMO_ATTR_FLEX_ARRIVAL))) {
    3056          150 :         SUMOTime flexStart = string2time(stop.pars.getParameter(toString(SUMO_ATTR_FLEX_ARRIVAL)));
    3057           75 :         arrivalDelay += STEPS2TIME(stop.pars.arrival - flexStart);
    3058           75 :         t = STEPS2TIME(flexStart - SIMSTEP);
    3059         2711 :     } else if (stop.pars.started >= 0 && MSGlobals::gUseStopStarted) {
    3060          200 :         arrivalDelay += STEPS2TIME(stop.pars.arrival - stop.pars.started);
    3061          200 :         t = STEPS2TIME(stop.pars.started - SIMSTEP);
    3062              :     }
    3063         2786 :     if (arrivalDelay < 0 && sfp < getChosenSpeedFactor()) {
    3064              :         // we can slow down to better match the schedule (and increase energy efficiency)
    3065         2721 :         const double vSlowDownMin = MAX2(myLane->getSpeedLimit() * sfp, vMinComfortable);
    3066         2721 :         const double s = timeDist.second;
    3067              :         const double b = getCarFollowModel().getMaxDecel();
    3068              :         // x = speed for arriving in t seconds
    3069              :         // u = time at full speed
    3070              :         // u * x + (t - u) * 0.5 * x = s
    3071              :         // t - u = x / b
    3072              :         // eliminate u, solve x
    3073         2721 :         const double radicand = 4 * t * t * b * b - 8 * s * b;
    3074         2721 :         const double x = radicand >= 0 ? t * b - sqrt(radicand) * 0.5 : vSlowDownMin;
    3075         2721 :         double vSlowDown = x < vSlowDownMin ? vSlowDownMin : x;
    3076              : #ifdef DEBUG_PLAN_MOVE
    3077              :         if (DEBUG_COND) {
    3078              :             std::cout << SIMTIME << " veh=" << getID() << " ad=" << arrivalDelay << " t=" << t << " vsm=" << vSlowDownMin
    3079              :                       << " r=" << radicand << " vs=" << vSlowDown << "\n";
    3080              :         }
    3081              : #endif
    3082         2721 :         return vSlowDown;
    3083           65 :     } else if (arrivalDelay > 0 && sfp > getChosenSpeedFactor()) {
    3084              :         // in principle we could up to catch up with the schedule
    3085              :         // but at this point we can only lower the speed, the
    3086              :         // information would have to be used when computing getVehicleMaxSpeed
    3087              :     }
    3088           65 :     return getMaxSpeed();
    3089              : }
    3090              : 
    3091              : SUMOTime
    3092    809514415 : MSVehicle::getArrivalTime(SUMOTime t, double seen, double v, double arrivalSpeed) const {
    3093              :     const MSCFModel& cfModel = getCarFollowModel();
    3094              :     SUMOTime arrivalTime;
    3095    809514415 :     if (MSGlobals::gSemiImplicitEulerUpdate) {
    3096              :         // @note intuitively it would make sense to compare arrivalSpeed with getSpeed() instead of v
    3097              :         // however, due to the current position update rule (ticket #860) the vehicle moves with v in this step
    3098              :         // subtract DELTA_T because t is the time at the end of this step and the movement is not carried out yet
    3099    753452081 :         arrivalTime = t - DELTA_T + cfModel.getMinimalArrivalTime(seen, v, arrivalSpeed);
    3100              :     } else {
    3101     56062334 :         arrivalTime = t - DELTA_T + cfModel.getMinimalArrivalTime(seen, myState.mySpeed, arrivalSpeed);
    3102              :     }
    3103    809514415 :     if (isStopped()) {
    3104      2344268 :         arrivalTime += MAX2((SUMOTime)0, myStops.front().duration);
    3105              :     }
    3106    809514415 :     return arrivalTime;
    3107              : }
    3108              : 
    3109              : 
    3110              : void
    3111   1156729464 : MSVehicle::adaptToLeaders(const MSLeaderInfo& ahead, double latOffset,
    3112              :                           const double seen, DriveProcessItem* const lastLink,
    3113              :                           const MSLane* const lane, double& v, double& vLinkPass) const {
    3114              :     int rightmost;
    3115              :     int leftmost;
    3116   1156729464 :     ahead.getSubLanes(this, latOffset, rightmost, leftmost);
    3117              : #ifdef DEBUG_PLAN_MOVE
    3118              :     if (DEBUG_COND) std::cout << SIMTIME
    3119              :                                   << "\nADAPT_TO_LEADERS\nveh=" << getID()
    3120              :                                   << " lane=" << lane->getID()
    3121              :                                   << " latOffset=" << latOffset
    3122              :                                   << " rm=" << rightmost
    3123              :                                   << " lm=" << leftmost
    3124              :                                   << " shift=" << ahead.getSublaneOffset()
    3125              :                                   << " ahead=" << ahead.toString()
    3126              :                                   << "\n";
    3127              : #endif
    3128              :     /*
    3129              :     if (myLaneChangeModel->getCommittedSpeed() > 0) {
    3130              :         v = MIN2(v, myLaneChangeModel->getCommittedSpeed());
    3131              :         vLinkPass = MIN2(vLinkPass, myLaneChangeModel->getCommittedSpeed());
    3132              :     #ifdef DEBUG_PLAN_MOVE
    3133              :         if (DEBUG_COND) std::cout << "   hasCommitted=" << myLaneChangeModel->getCommittedSpeed() << "\n";
    3134              :     #endif
    3135              :         return;
    3136              :     }
    3137              :     */
    3138   2850232167 :     for (int sublane = rightmost; sublane <= leftmost; ++sublane) {
    3139   1693502703 :         const MSVehicle* pred = ahead[sublane];
    3140   1693502703 :         if (pred != nullptr && pred != this) {
    3141              :             // @todo avoid multiple adaptations to the same leader
    3142   1238909085 :             const double predBack = pred->getBackPositionOnLane(lane);
    3143              :             double gap = (lastLink == nullptr
    3144   1768455286 :                           ? predBack - myState.myPos - getVehicleType().getMinGap()
    3145    529546201 :                           : predBack + seen - lane->getLength() - getVehicleType().getMinGap());
    3146              :             bool oncoming = false;
    3147   1238909085 :             if (myLaneChangeModel->isOpposite()) {
    3148        26723 :                 if (pred->getLaneChangeModel().isOpposite() || lane == pred->getLaneChangeModel().getShadowLane()) {
    3149              :                     // ego might and leader are driving against lane
    3150              :                     gap = (lastLink == nullptr
    3151            0 :                            ? myState.myPos - predBack - getVehicleType().getMinGap()
    3152            0 :                            : predBack + seen - lane->getLength() - getVehicleType().getMinGap());
    3153              :                 } else {
    3154              :                     // ego and leader are driving in the same direction as lane (shadowlane for ego)
    3155              :                     gap = (lastLink == nullptr
    3156        27424 :                            ? predBack - (myLane->getLength() - myState.myPos) - getVehicleType().getMinGap()
    3157          701 :                            : predBack + seen - lane->getLength() - getVehicleType().getMinGap());
    3158              :                 }
    3159   1238882362 :             } else if (pred->getLaneChangeModel().isOpposite() && pred->getLaneChangeModel().getShadowLane() != lane) {
    3160              :                 // must react to stopped / dangerous oncoming vehicles
    3161       192013 :                 gap += -pred->getVehicleType().getLength() + getVehicleType().getMinGap() - MAX2(getVehicleType().getMinGap(), pred->getVehicleType().getMinGap());
    3162              :                 // try to avoid collision in the next second
    3163       192013 :                 const double predMaxDist = pred->getSpeed() + pred->getCarFollowModel().getMaxAccel();
    3164              : #ifdef DEBUG_PLAN_MOVE
    3165              :                 if (DEBUG_COND) {
    3166              :                     std::cout << "    fixedGap=" << gap << " predMaxDist=" << predMaxDist << "\n";
    3167              :                 }
    3168              : #endif
    3169       192013 :                 if (gap < predMaxDist + getSpeed() || pred->getLane() == lane->getBidiLane()) {
    3170        23356 :                     gap -= predMaxDist;
    3171              :                 }
    3172   1238690349 :             } else if (pred->getLane() == lane->getBidiLane()) {
    3173        48517 :                 gap -= pred->getVehicleType().getLengthWithGap();
    3174              :                 oncoming = true;
    3175              :             }
    3176              : #ifdef DEBUG_PLAN_MOVE
    3177              :             if (DEBUG_COND) {
    3178              :                 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";
    3179              :             }
    3180              : #endif
    3181        48517 :             if (oncoming && gap >= 0) {
    3182        48506 :                 adaptToOncomingLeader(std::make_pair(pred, gap), lastLink, v, vLinkPass);
    3183              :             } else {
    3184   1238860579 :                 adaptToLeader(std::make_pair(pred, gap), seen, lastLink, v, vLinkPass);
    3185              :             }
    3186              :         }
    3187              :     }
    3188   1156729464 : }
    3189              : 
    3190              : void
    3191       431607 : MSVehicle::adaptToLeaderDistance(const MSLeaderDistanceInfo& ahead, double latOffset,
    3192              :                                  double seen,
    3193              :                                  DriveProcessItem* const lastLink,
    3194              :                                  double& v, double& vLinkPass) const {
    3195              :     int rightmost;
    3196              :     int leftmost;
    3197       431607 :     ahead.getSubLanes(this, latOffset, rightmost, leftmost);
    3198              : #ifdef DEBUG_PLAN_MOVE
    3199              :     if (DEBUG_COND) std::cout << SIMTIME
    3200              :                                   << "\nADAPT_TO_LEADERS_DISTANCE\nveh=" << getID()
    3201              :                                   << " latOffset=" << latOffset
    3202              :                                   << " rm=" << rightmost
    3203              :                                   << " lm=" << leftmost
    3204              :                                   << " ahead=" << ahead.toString()
    3205              :                                   << "\n";
    3206              : #endif
    3207      1058204 :     for (int sublane = rightmost; sublane <= leftmost; ++sublane) {
    3208       626597 :         CLeaderDist predDist = ahead[sublane];
    3209       626597 :         const MSVehicle* pred = predDist.first;
    3210       626597 :         if (pred != nullptr && pred != this) {
    3211              : #ifdef DEBUG_PLAN_MOVE
    3212              :             if (DEBUG_COND) {
    3213              :                 std::cout << "     pred=" << pred->getID() << " predLane=" << pred->getLane()->getID() << " predPos=" << pred->getPositionOnLane() << " gap=" << predDist.second << "\n";
    3214              :             }
    3215              : #endif
    3216       400207 :             adaptToLeader(predDist, seen, lastLink, v, vLinkPass);
    3217              :         }
    3218              :     }
    3219       431607 : }
    3220              : 
    3221              : 
    3222              : void
    3223   1239260786 : MSVehicle::adaptToLeader(const std::pair<const MSVehicle*, double> leaderInfo,
    3224              :                          double seen,
    3225              :                          DriveProcessItem* const lastLink,
    3226              :                          double& v, double& vLinkPass) const {
    3227   1239260786 :     if (leaderInfo.first != 0) {
    3228   1239260786 :         if (ignoreFoe(leaderInfo.first)) {
    3229              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3230              :             if (DEBUG_COND) {
    3231              :                 std::cout << "  foe ignored\n";
    3232              :             }
    3233              : #endif
    3234              :             return;
    3235              :         }
    3236              :         const MSCFModel& cfModel = getCarFollowModel();
    3237              :         double vsafeLeader = 0;
    3238   1239259966 :         if (!MSGlobals::gSemiImplicitEulerUpdate) {
    3239              :             vsafeLeader = -std::numeric_limits<double>::max();
    3240              :         }
    3241              :         bool backOnRoute = true;
    3242   1239259966 :         if (leaderInfo.second < 0 && lastLink != nullptr && lastLink->myLink != nullptr) {
    3243              :             backOnRoute = false;
    3244              :             // this can either be
    3245              :             // a) a merging situation (leader back is is not our route) or
    3246              :             // b) a minGap violation / collision
    3247              :             MSLane* current = lastLink->myLink->getViaLaneOrLane();
    3248       232754 :             if (leaderInfo.first->getBackLane() == current) {
    3249              :                 backOnRoute = true;
    3250              :             } else {
    3251       521081 :                 for (MSLane* lane : getBestLanesContinuation()) {
    3252       482548 :                     if (lane == current) {
    3253              :                         break;
    3254              :                     }
    3255       333907 :                     if (leaderInfo.first->getBackLane() == lane) {
    3256              :                         backOnRoute = true;
    3257              :                     }
    3258              :                 }
    3259              :             }
    3260              : #ifdef DEBUG_PLAN_MOVE
    3261              :             if (DEBUG_COND) {
    3262              :                 std::cout << SIMTIME << " current=" << current->getID() << " leaderBackLane=" << leaderInfo.first->getBackLane()->getID() << " backOnRoute=" << backOnRoute << "\n";
    3263              :             }
    3264              : #endif
    3265       187174 :             if (!backOnRoute) {
    3266       117004 :                 double stopDist = seen - current->getLength() - POSITION_EPS;
    3267       117004 :                 if (lastLink->myLink->getInternalLaneBefore() != nullptr) {
    3268              :                     // do not drive onto the junction conflict area
    3269       102518 :                     stopDist -= lastLink->myLink->getInternalLaneBefore()->getLength();
    3270              :                 }
    3271       117004 :                 vsafeLeader = cfModel.stopSpeed(this, getSpeed(), stopDist);
    3272              :             }
    3273              :         }
    3274       162584 :         if (backOnRoute) {
    3275   1239142962 :             vsafeLeader = cfModel.followSpeed(this, getSpeed(), leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first);
    3276              :         }
    3277   1239259966 :         if (lastLink != nullptr) {
    3278    529537290 :             const double futureVSafe = cfModel.followSpeed(this, lastLink->accelV, leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first, MSCFModel::CalcReason::FUTURE);
    3279              :             lastLink->adaptLeaveSpeed(futureVSafe);
    3280              : #ifdef DEBUG_PLAN_MOVE
    3281              :             if (DEBUG_COND) {
    3282              :                 std::cout << "   vlinkpass=" << lastLink->myVLinkPass << " futureVSafe=" << futureVSafe << "\n";
    3283              :             }
    3284              : #endif
    3285              :         }
    3286   1239259966 :         v = MIN2(v, vsafeLeader);
    3287   2130590554 :         vLinkPass = MIN2(vLinkPass, vsafeLeader);
    3288              : #ifdef DEBUG_PLAN_MOVE
    3289              :         if (DEBUG_COND) std::cout
    3290              :                     << SIMTIME
    3291              :                     //std::cout << std::setprecision(10);
    3292              :                     << " veh=" << getID()
    3293              :                     << " lead=" << leaderInfo.first->getID()
    3294              :                     << " leadSpeed=" << leaderInfo.first->getSpeed()
    3295              :                     << " gap=" << leaderInfo.second
    3296              :                     << " leadLane=" << leaderInfo.first->getLane()->getID()
    3297              :                     << " predPos=" << leaderInfo.first->getPositionOnLane()
    3298              :                     << " myLane=" << myLane->getID()
    3299              :                     << " v=" << v
    3300              :                     << " vSafeLeader=" << vsafeLeader
    3301              :                     << " vLinkPass=" << vLinkPass
    3302              :                     << "\n";
    3303              : #endif
    3304              :     }
    3305              : }
    3306              : 
    3307              : 
    3308              : void
    3309     17551246 : MSVehicle::adaptToJunctionLeader(const std::pair<const MSVehicle*, double> leaderInfo,
    3310              :                                  const double seen, DriveProcessItem* const lastLink,
    3311              :                                  const MSLane* const lane, double& v, double& vLinkPass,
    3312              :                                  double distToCrossing) const {
    3313     17551246 :     if (leaderInfo.first != 0) {
    3314     17551246 :         if (ignoreFoe(leaderInfo.first)) {
    3315              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3316              :             if (DEBUG_COND) {
    3317              :                 std::cout << "  junction foe ignored\n";
    3318              :             }
    3319              : #endif
    3320              :             return;
    3321              :         }
    3322              :         const MSCFModel& cfModel = getCarFollowModel();
    3323              :         double vsafeLeader = 0;
    3324     17551210 :         if (!MSGlobals::gSemiImplicitEulerUpdate) {
    3325              :             vsafeLeader = -std::numeric_limits<double>::max();
    3326              :         }
    3327     17551210 :         if (leaderInfo.second >= 0) {
    3328     14483178 :             if (hasDeparted()) {
    3329     14478166 :                 vsafeLeader = cfModel.followSpeed(this, getSpeed(), leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first);
    3330              :             } else {
    3331              :                 // called in the context of MSLane::isInsertionSuccess
    3332         5012 :                 vsafeLeader = cfModel.insertionFollowSpeed(this, getSpeed(), leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first);
    3333              :             }
    3334      3068032 :         } else if (leaderInfo.first != this) {
    3335              :             // the leading, in-lapping vehicle is occupying the complete next lane
    3336              :             // stop before entering this lane
    3337      2667538 :             vsafeLeader = cfModel.stopSpeed(this, getSpeed(), seen - lane->getLength() - POSITION_EPS);
    3338              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3339              :             if (DEBUG_COND) {
    3340              :                 std::cout << SIMTIME << " veh=" << getID() << "  stopping before junction: lane=" << lane->getID() << " seen=" << seen
    3341              :                           << " laneLength=" << lane->getLength()
    3342              :                           << " stopDist=" << seen - lane->getLength()  - POSITION_EPS
    3343              :                           << " vsafeLeader=" << vsafeLeader
    3344              :                           << " distToCrossing=" << distToCrossing
    3345              :                           << "\n";
    3346              :             }
    3347              : #endif
    3348              :         }
    3349     17551210 :         if (distToCrossing >= 0) {
    3350              :             // can the leader still stop in the way?
    3351      5224649 :             const double vStop = cfModel.stopSpeed(this, getSpeed(), distToCrossing - getVehicleType().getMinGap());
    3352      5224649 :             if (leaderInfo.first == this) {
    3353              :                 // braking for pedestrian
    3354       391811 :                 const double vStopCrossing = cfModel.stopSpeed(this, getSpeed(), distToCrossing);
    3355              :                 vsafeLeader = vStopCrossing;
    3356              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3357              :                 if (DEBUG_COND) {
    3358              :                     std::cout << "  breaking for pedestrian distToCrossing=" << distToCrossing << " vStopCrossing=" << vStopCrossing << "\n";
    3359              :                 }
    3360              : #endif
    3361       391811 :                 if (lastLink != nullptr) {
    3362              :                     lastLink->adaptStopSpeed(vsafeLeader);
    3363              :                 }
    3364      4832838 :             } else if (leaderInfo.second == -std::numeric_limits<double>::max()) {
    3365              :                 // drive up to the crossing point and stop
    3366              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3367              :                 if (DEBUG_COND) {
    3368              :                     std::cout << "  stop at crossing point for critical leader vStop=" << vStop << "\n";
    3369              :                 };
    3370              : #endif
    3371              :                 vsafeLeader = MAX2(vsafeLeader, vStop);
    3372              :             } else {
    3373      4777185 :                 const double leaderDistToCrossing = distToCrossing - leaderInfo.second;
    3374              :                 // estimate the time at which the leader has gone past the crossing point
    3375      4777185 :                 const double leaderPastCPTime = leaderDistToCrossing / MAX2(leaderInfo.first->getSpeed(), SUMO_const_haltingSpeed);
    3376              :                 // reach distToCrossing after that time
    3377              :                 // avgSpeed * leaderPastCPTime = distToCrossing
    3378              :                 // ballistic: avgSpeed = (getSpeed + vFinal) / 2
    3379      4777185 :                 const double vFinal = MAX2(getSpeed(), 2 * (distToCrossing - getVehicleType().getMinGap()) / leaderPastCPTime - getSpeed());
    3380      4777185 :                 const double v2 = getSpeed() + ACCEL2SPEED((vFinal - getSpeed()) / leaderPastCPTime);
    3381              :                 vsafeLeader = MAX2(vsafeLeader, MIN2(v2, vStop));
    3382              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3383              :                 if (DEBUG_COND) {
    3384              :                     std::cout << "    driving up to the crossing point (distToCrossing=" << distToCrossing << ")"
    3385              :                               << " leaderPastCPTime=" << leaderPastCPTime
    3386              :                               << " vFinal=" << vFinal
    3387              :                               << " v2=" << v2
    3388              :                               << " vStop=" << vStop
    3389              :                               << " vsafeLeader=" << vsafeLeader << "\n";
    3390              :                 }
    3391              : #endif
    3392              :             }
    3393              :         }
    3394     17159399 :         if (lastLink != nullptr) {
    3395              :             lastLink->adaptLeaveSpeed(vsafeLeader);
    3396              :         }
    3397     17551210 :         v = MIN2(v, vsafeLeader);
    3398     32789157 :         vLinkPass = MIN2(vLinkPass, vsafeLeader);
    3399              : #ifdef DEBUG_PLAN_MOVE
    3400              :         if (DEBUG_COND) std::cout
    3401              :                     << SIMTIME
    3402              :                     //std::cout << std::setprecision(10);
    3403              :                     << " veh=" << getID()
    3404              :                     << " lead=" << leaderInfo.first->getID()
    3405              :                     << " leadSpeed=" << leaderInfo.first->getSpeed()
    3406              :                     << " gap=" << leaderInfo.second
    3407              :                     << " leadLane=" << leaderInfo.first->getLane()->getID()
    3408              :                     << " predPos=" << leaderInfo.first->getPositionOnLane()
    3409              :                     << " seen=" << seen
    3410              :                     << " lane=" << lane->getID()
    3411              :                     << " myLane=" << myLane->getID()
    3412              :                     << " dTC=" << distToCrossing
    3413              :                     << " v=" << v
    3414              :                     << " vSafeLeader=" << vsafeLeader
    3415              :                     << " vLinkPass=" << vLinkPass
    3416              :                     << "\n";
    3417              : #endif
    3418              :     }
    3419              : }
    3420              : 
    3421              : 
    3422              : void
    3423        48506 : MSVehicle::adaptToOncomingLeader(const std::pair<const MSVehicle*, double> leaderInfo,
    3424              :                                  DriveProcessItem* const lastLink,
    3425              :                                  double& v, double& vLinkPass) const {
    3426        48506 :     if (leaderInfo.first != 0) {
    3427        48506 :         if (ignoreFoe(leaderInfo.first)) {
    3428              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3429              :             if (DEBUG_COND) {
    3430              :                 std::cout << "  oncoming foe ignored\n";
    3431              :             }
    3432              : #endif
    3433              :             return;
    3434              :         }
    3435              :         const MSCFModel& cfModel = getCarFollowModel();
    3436              :         const MSVehicle* lead = leaderInfo.first;
    3437              :         const MSCFModel& cfModelL = lead->getCarFollowModel();
    3438              :         // assume the leader reacts symmetrically (neither stopping instantly nor ignoring ego)
    3439        48387 :         const double leaderBrakeGap = cfModelL.brakeGap(lead->getSpeed(), cfModelL.getMaxDecel(), 0);
    3440        48387 :         const double egoBrakeGap = cfModel.brakeGap(getSpeed(), cfModel.getMaxDecel(), 0);
    3441        48387 :         const double gapSum = leaderBrakeGap + egoBrakeGap;
    3442              :         // ensure that both vehicles can leave an intersection if they are currently on it
    3443        48387 :         double egoExit = getDistanceToLeaveJunction();
    3444        48387 :         const double leaderExit = lead->getDistanceToLeaveJunction();
    3445              :         double gap = leaderInfo.second;
    3446        48387 :         if (egoExit + leaderExit < gap) {
    3447        44638 :             gap -= egoExit + leaderExit;
    3448              :         } else {
    3449              :             egoExit = 0;
    3450              :         }
    3451              :         // split any distance in excess of brakeGaps evenly
    3452        48387 :         const double freeGap = MAX2(0.0, gap - gapSum);
    3453              :         const double splitGap = MIN2(gap, gapSum);
    3454              :         // assume remaining distance is allocated in proportion to braking distance
    3455        48387 :         const double gapRatio = gapSum > 0 ? egoBrakeGap / gapSum : 0.5;
    3456        48387 :         const double vsafeLeader = cfModel.stopSpeed(this, getSpeed(), splitGap * gapRatio + egoExit + 0.5 * freeGap);
    3457        48387 :         if (lastLink != nullptr) {
    3458        28735 :             const double futureVSafe = cfModel.stopSpeed(this, lastLink->accelV, leaderInfo.second, MSCFModel::CalcReason::FUTURE);
    3459              :             lastLink->adaptLeaveSpeed(futureVSafe);
    3460              : #ifdef DEBUG_PLAN_MOVE
    3461              :             if (DEBUG_COND) {
    3462              :                 std::cout << "   vlinkpass=" << lastLink->myVLinkPass << " futureVSafe=" << futureVSafe << "\n";
    3463              :             }
    3464              : #endif
    3465              :         }
    3466        48387 :         v = MIN2(v, vsafeLeader);
    3467        95355 :         vLinkPass = MIN2(vLinkPass, vsafeLeader);
    3468              : #ifdef DEBUG_PLAN_MOVE
    3469              :         if (DEBUG_COND) std::cout
    3470              :                     << SIMTIME
    3471              :                     //std::cout << std::setprecision(10);
    3472              :                     << " veh=" << getID()
    3473              :                     << " oncomingLead=" << lead->getID()
    3474              :                     << " leadSpeed=" << lead->getSpeed()
    3475              :                     << " gap=" << leaderInfo.second
    3476              :                     << " gap2=" << gap
    3477              :                     << " gapRatio=" << gapRatio
    3478              :                     << " leadLane=" << lead->getLane()->getID()
    3479              :                     << " predPos=" << lead->getPositionOnLane()
    3480              :                     << " myLane=" << myLane->getID()
    3481              :                     << " v=" << v
    3482              :                     << " vSafeLeader=" << vsafeLeader
    3483              :                     << " vLinkPass=" << vLinkPass
    3484              :                     << "\n";
    3485              : #endif
    3486              :     }
    3487              : }
    3488              : 
    3489              : 
    3490              : void
    3491    754378793 : MSVehicle::checkLinkLeaderCurrentAndParallel(const MSLink* link, const MSLane* lane, double seen,
    3492              :         DriveProcessItem* const lastLink, double& v, double& vLinkPass, double& vLinkWait, bool& setRequest) const {
    3493    754378793 :     if (MSGlobals::gUsingInternalLanes && (myInfluencer == nullptr || myInfluencer->getRespectJunctionLeaderPriority())) {
    3494              :         // we want to pass the link but need to check for foes on internal lanes
    3495    754272833 :         checkLinkLeader(link, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest);
    3496    754272833 :         if (myLaneChangeModel->getShadowLane() != nullptr) {
    3497      3045135 :             const MSLink* const parallelLink = link->getParallelLink(myLaneChangeModel->getShadowDirection());
    3498      3045135 :             if (parallelLink != nullptr) {
    3499      2103706 :                 checkLinkLeader(parallelLink, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest, true);
    3500              :             }
    3501              :         }
    3502              :     }
    3503              : 
    3504    754378793 : }
    3505              : 
    3506              : void
    3507    756581353 : MSVehicle::checkLinkLeader(const MSLink* link, const MSLane* lane, double seen,
    3508              :                            DriveProcessItem* const lastLink, double& v, double& vLinkPass, double& vLinkWait, bool& setRequest,
    3509              :                            bool isShadowLink) const {
    3510              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3511              :     if (DEBUG_COND) {
    3512              :         gDebugFlag1 = true;    // See MSLink::getLeaderInfo
    3513              :     }
    3514              : #endif
    3515    756581353 :     const MSLink::LinkLeaders linkLeaders = link->getLeaderInfo(this, seen, nullptr, isShadowLink);
    3516              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3517              :     if (DEBUG_COND) {
    3518              :         gDebugFlag1 = false;    // See MSLink::getLeaderInfo
    3519              :     }
    3520              : #endif
    3521    775071831 :     for (MSLink::LinkLeaders::const_iterator it = linkLeaders.begin(); it != linkLeaders.end(); ++it) {
    3522              :         // the vehicle to enter the junction first has priority
    3523     18490478 :         const MSVehicle* leader = (*it).vehAndGap.first;
    3524     18490478 :         if (leader == nullptr) {
    3525              :             // leader is a pedestrian. Passing 'this' as a dummy.
    3526              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3527              :             if (DEBUG_COND) {
    3528              :                 std::cout << SIMTIME << " veh=" << getID() << " is blocked on link to " << link->getViaLaneOrLane()->getID() << " by pedestrian. dist=" << it->distToCrossing << "\n";
    3529              :             }
    3530              : #endif
    3531       401190 :             if (getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_JUNCTION_FOE_PROB, 0) > 0
    3532       401190 :                     && getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_JUNCTION_FOE_PROB, 0) >= RandHelper::rand(getRNG())) {
    3533              : #ifdef DEBUG_PLAN_MOVE
    3534              :                 if (DEBUG_COND) {
    3535              :                     std::cout << SIMTIME << " veh=" << getID() << " is ignoring pedestrian (jmIgnoreJunctionFoeProb)\n";
    3536              :                 }
    3537              : #endif
    3538          696 :                 continue;
    3539              :             }
    3540       400494 :             adaptToJunctionLeader(std::make_pair(this, -1), seen, lastLink, lane, v, vLinkPass, it->distToCrossing);
    3541              :             // if blocked by a pedestrian for too long we must yield our request
    3542       400494 :             if (v < SUMO_const_haltingSpeed && getWaitingTime() > TIME2STEPS(JUNCTION_BLOCKAGE_TIME)) {
    3543        69939 :                 setRequest = false;
    3544              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3545              :                 if (DEBUG_COND) {
    3546              :                     std::cout << "   aborting request\n";
    3547              :                 }
    3548              : #endif
    3549              :             }
    3550     18089288 :         } else if (isLeader(link, leader, (*it).vehAndGap.second) || (*it).inTheWay()) {
    3551     18038375 :             if (getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_JUNCTION_FOE_PROB, 0) > 0
    3552     18038375 :                     && getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_JUNCTION_FOE_PROB, 0) >= RandHelper::rand(getRNG())) {
    3553              : #ifdef DEBUG_PLAN_MOVE
    3554              :                 if (DEBUG_COND) {
    3555              :                     std::cout << SIMTIME << " veh=" << getID() << " is ignoring linkLeader=" << leader->getID() << " (jmIgnoreJunctionFoeProb)\n";
    3556              :                 }
    3557              : #endif
    3558         2181 :                 continue;
    3559              :             }
    3560     24768602 :             if (MSGlobals::gLateralResolution > 0 &&
    3561              :                     // sibling link (XXX: could also be partial occupator where this check fails)
    3562      6732408 :                     &leader->getLane()->getEdge() == &lane->getEdge()) {
    3563              :                 // check for sublane obstruction (trivial for sibling link leaders)
    3564              :                 const MSLane* conflictLane = link->getInternalLaneBefore();
    3565       908295 :                 MSLeaderInfo linkLeadersAhead = MSLeaderInfo(conflictLane->getWidth());
    3566       908295 :                 linkLeadersAhead.addLeader(leader, false, 0); // assume sibling lane has the same geometry as the leader lane
    3567       908295 :                 const double latOffset = isShadowLink ? (getLane()->getRightSideOnEdge() - myLaneChangeModel->getShadowLane()->getRightSideOnEdge()) : 0;
    3568              :                 // leader is neither on lane nor conflictLane (the conflict is only established geometrically)
    3569       908295 :                 adaptToLeaders(linkLeadersAhead, latOffset, seen, lastLink, leader->getLane(), v, vLinkPass);
    3570              : #ifdef DEBUG_PLAN_MOVE
    3571              :                 if (DEBUG_COND) {
    3572              :                     std::cout << SIMTIME << " veh=" << getID()
    3573              :                               << " siblingFoe link=" << link->getViaLaneOrLane()->getID()
    3574              :                               << " isShadowLink=" << isShadowLink
    3575              :                               << " lane=" << lane->getID()
    3576              :                               << " foe=" << leader->getID()
    3577              :                               << " foeLane=" << leader->getLane()->getID()
    3578              :                               << " latOffset=" << latOffset
    3579              :                               << " latOffsetFoe=" << leader->getLatOffset(lane)
    3580              :                               << " linkLeadersAhead=" << linkLeadersAhead.toString()
    3581              :                               << "\n";
    3582              :                 }
    3583              : #endif
    3584       908295 :             } else {
    3585              : #ifdef DEBUG_PLAN_MOVE
    3586              :                 if (DEBUG_COND) {
    3587              :                     std::cout << SIMTIME << " veh=" << getID() << " linkLeader=" << leader->getID() << " gap=" << it->vehAndGap.second
    3588              :                               << " ET=" << myJunctionEntryTime << " lET=" << leader->myJunctionEntryTime
    3589              :                               << " ETN=" << myJunctionEntryTimeNeverYield << " lETN=" << leader->myJunctionEntryTimeNeverYield
    3590              :                               << " CET=" << myJunctionConflictEntryTime << " lCET=" << leader->myJunctionConflictEntryTime
    3591              :                               << "\n";
    3592              :                 }
    3593              : #endif
    3594     17127899 :                 adaptToJunctionLeader(it->vehAndGap, seen, lastLink, lane, v, vLinkPass, it->distToCrossing);
    3595              :             }
    3596     18036194 :             if (lastLink != nullptr) {
    3597              :                 // we are not yet on the junction with this linkLeader.
    3598              :                 // at least we can drive up to the previous link and stop there
    3599     34672365 :                 v = MAX2(v, lastLink->myVLinkWait);
    3600              :             }
    3601              :             // if blocked by a leader from the same or next lane we must yield our request
    3602              :             // also, if blocked by a stopped or blocked leader
    3603     18036194 :             if (v < SUMO_const_haltingSpeed
    3604              :                     //&& leader->getSpeed() < SUMO_const_haltingSpeed
    3605     18036194 :                     && (leader->getLane()->getLogicalPredecessorLane() == myLane->getLogicalPredecessorLane()
    3606      9964956 :                         || leader->getLane()->getLogicalPredecessorLane() == myLane
    3607      7796615 :                         || leader->isStopped()
    3608      7716250 :                         || leader->getWaitingTime() > TIME2STEPS(JUNCTION_BLOCKAGE_TIME))) {
    3609      4113788 :                 setRequest = false;
    3610              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3611              :                 if (DEBUG_COND) {
    3612              :                     std::cout << "   aborting request\n";
    3613              :                 }
    3614              : #endif
    3615      4113788 :                 if (lastLink != nullptr && leader->getLane()->getLogicalPredecessorLane() == myLane) {
    3616              :                     // we are not yet on the junction so must abort that request as well
    3617              :                     // (or maybe we are already on the junction and the leader is a partial occupator beyond)
    3618      2154902 :                     lastLink->mySetRequest = false;
    3619              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3620              :                     if (DEBUG_COND) {
    3621              :                         std::cout << "      aborting previous request\n";
    3622              :                     }
    3623              : #endif
    3624              :                 }
    3625              :             }
    3626              :         }
    3627              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3628              :         else {
    3629              :             if (DEBUG_COND) {
    3630              :                 std::cout << SIMTIME << " veh=" << getID() << " ignoring leader " << leader->getID() << " gap=" << (*it).vehAndGap.second << " dtC=" << (*it).distToCrossing
    3631              :                           << " ET=" << myJunctionEntryTime << " lET=" << leader->myJunctionEntryTime
    3632              :                           << " ETN=" << myJunctionEntryTimeNeverYield << " lETN=" << leader->myJunctionEntryTimeNeverYield
    3633              :                           << " CET=" << myJunctionConflictEntryTime << " lCET=" << leader->myJunctionConflictEntryTime
    3634              :                           << "\n";
    3635              :             }
    3636              :         }
    3637              : #endif
    3638              :     }
    3639              :     // if this is the link between two internal lanes we may have to slow down for pedestrians
    3640    756581353 :     vLinkWait = MIN2(vLinkWait, v);
    3641    756581353 : }
    3642              : 
    3643              : 
    3644              : double
    3645     99579974 : MSVehicle::getDeltaPos(const double accel) const {
    3646     99579974 :     double vNext = myState.mySpeed + ACCEL2SPEED(accel);
    3647     99579974 :     if (MSGlobals::gSemiImplicitEulerUpdate) {
    3648              :         // apply implicit Euler positional update
    3649            0 :         return SPEED2DIST(MAX2(vNext, 0.));
    3650              :     } else {
    3651              :         // apply ballistic update
    3652     99579974 :         if (vNext >= 0) {
    3653              :             // assume constant acceleration during this time step
    3654     98964831 :             return SPEED2DIST(myState.mySpeed + 0.5 * ACCEL2SPEED(accel));
    3655              :         } else {
    3656              :             // negative vNext indicates a stop within the middle of time step
    3657              :             // The corresponding stop time is s = mySpeed/deceleration \in [0,dt], and the
    3658              :             // covered distance is therefore deltaPos = mySpeed*s - 0.5*deceleration*s^2.
    3659              :             // Here, deceleration = (myState.mySpeed - vNext)/dt is the constant deceleration
    3660              :             // until the vehicle stops.
    3661       615143 :             return -SPEED2DIST(0.5 * myState.mySpeed * myState.mySpeed / ACCEL2SPEED(accel));
    3662              :         }
    3663              :     }
    3664              : }
    3665              : 
    3666              : void
    3667    608595485 : MSVehicle::processLinkApproaches(double& vSafe, double& vSafeMin, double& vSafeMinDist) {
    3668              : 
    3669              :     // Speed limit due to zipper merging
    3670              :     double vSafeZipper = std::numeric_limits<double>::max();
    3671              : 
    3672    608595485 :     myHaveToWaitOnNextLink = false;
    3673              :     bool canBrakeVSafeMin = false;
    3674              : 
    3675              :     // Get safe velocities from DriveProcessItems.
    3676              :     assert(myLFLinkLanes.size() != 0 || isRemoteControlled());
    3677   1208997743 :     for (const DriveProcessItem& dpi : myLFLinkLanes) {
    3678   1040123815 :         MSLink* const link = dpi.myLink;
    3679              : 
    3680              : #ifdef DEBUG_EXEC_MOVE
    3681              :         if (DEBUG_COND) {
    3682              :             std::cout
    3683              :                     << SIMTIME
    3684              :                     << " veh=" << getID()
    3685              :                     << " link=" << (link == 0 ? "NULL" : link->getViaLaneOrLane()->getID())
    3686              :                     << " req=" << dpi.mySetRequest
    3687              :                     << " vP=" << dpi.myVLinkPass
    3688              :                     << " vW=" << dpi.myVLinkWait
    3689              :                     << " d=" << dpi.myDistance
    3690              :                     << "\n";
    3691              :             gDebugFlag1 = true; // See MSLink_DEBUG_OPENED
    3692              :         }
    3693              : #endif
    3694              : 
    3695              :         // the vehicle must change the lane on one of the next lanes (XXX: refs to code further below???, Leo)
    3696   1040123815 :         if (link != nullptr && dpi.mySetRequest) {
    3697              : 
    3698              :             const LinkState ls = link->getState();
    3699              :             // vehicles should brake when running onto a yellow light if the distance allows to halt in front
    3700              :             const bool yellow = link->haveYellow();
    3701    620392560 :             const bool canBrake = (dpi.myDistance > getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0.)
    3702    620392560 :                                    || (MSGlobals::gSemiImplicitEulerUpdate && myState.mySpeed < ACCEL2SPEED(getCarFollowModel().getMaxDecel())));
    3703              :             assert(link->getLaneBefore() != nullptr);
    3704    620392560 :             const bool beyondStopLine = dpi.myDistance < link->getLaneBefore()->getVehicleStopOffset(this);
    3705    620392560 :             const bool ignoreRedLink = ignoreRed(link, canBrake) || beyondStopLine;
    3706    620392560 :             if (yellow && canBrake && !ignoreRedLink) {
    3707            0 :                 vSafe = dpi.myVLinkWait;
    3708            0 :                 myHaveToWaitOnNextLink = true;
    3709              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3710              :                 if (DEBUG_COND) {
    3711              :                     std::cout << SIMTIME << " veh=" << getID() << " haveToWait (yellow)\n";
    3712              :                 }
    3713              : #endif
    3714     19990302 :                 break;
    3715              :             }
    3716    620392560 :             const bool influencerPrio = (myInfluencer != nullptr && !myInfluencer->getRespectJunctionPriority());
    3717              :             MSLink::BlockingFoes collectFoes;
    3718    620392560 :             bool opened = (yellow || influencerPrio
    3719   1860856646 :                            || link->opened(dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
    3720    620232043 :                                            getVehicleType().getLength(),
    3721    593403234 :                                            canBrake ? getImpatience() : 1,
    3722              :                                            getCarFollowModel().getMaxDecel(),
    3723    620232043 :                                            getWaitingTimeFor(link), getLateralPositionOnLane(),
    3724              :                                            ls == LINKSTATE_ZIPPER ? &collectFoes : nullptr,
    3725    620232043 :                                            ignoreRedLink, this, dpi.myDistance));
    3726    615149834 :             if (opened && myLaneChangeModel->getShadowLane() != nullptr) {
    3727      1901855 :                 const MSLink* const parallelLink = dpi.myLink->getParallelLink(myLaneChangeModel->getShadowDirection());
    3728      1901855 :                 if (parallelLink != nullptr) {
    3729      1175317 :                     const double shadowLatPos = getLateralPositionOnLane() - myLaneChangeModel->getShadowDirection() * 0.5 * (
    3730      1175317 :                                                     myLane->getWidth() + myLaneChangeModel->getShadowLane()->getWidth());
    3731      2349827 :                     opened = yellow || influencerPrio || (opened && parallelLink->opened(dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
    3732      1174510 :                                                           getVehicleType().getLength(), getImpatience(),
    3733              :                                                           getCarFollowModel().getMaxDecel(),
    3734              :                                                           getWaitingTimeFor(link), shadowLatPos, nullptr,
    3735      1174510 :                                                           ignoreRedLink, this, dpi.myDistance));
    3736              : #ifdef DEBUG_EXEC_MOVE
    3737              :                     if (DEBUG_COND) {
    3738              :                         std::cout << SIMTIME
    3739              :                                   << " veh=" << getID()
    3740              :                                   << " shadowLane=" << myLaneChangeModel->getShadowLane()->getID()
    3741              :                                   << " shadowDir=" << myLaneChangeModel->getShadowDirection()
    3742              :                                   << " parallelLink=" << (parallelLink == 0 ? "NULL" : parallelLink->getViaLaneOrLane()->getID())
    3743              :                                   << " opened=" << opened
    3744              :                                   << "\n";
    3745              :                     }
    3746              : #endif
    3747              :                 }
    3748              :             }
    3749              :             // vehicles should decelerate when approaching a minor link
    3750              : #ifdef DEBUG_EXEC_MOVE
    3751              :             if (DEBUG_COND) {
    3752              :                 std::cout << SIMTIME
    3753              :                           << "   opened=" << opened
    3754              :                           << " influencerPrio=" << influencerPrio
    3755              :                           << " linkPrio=" << link->havePriority()
    3756              :                           << " lastContMajor=" << link->lastWasContMajor()
    3757              :                           << " isCont=" << link->isCont()
    3758              :                           << " ignoreRed=" << ignoreRedLink
    3759              :                           << "\n";
    3760              :             }
    3761              : #endif
    3762              :             double visibilityDistance = link->getFoeVisibilityDistance();
    3763    620392560 :             bool determinedFoePresence = dpi.myDistance <= visibilityDistance;
    3764    620392560 :             if (opened && !influencerPrio && !link->havePriority() && !link->lastWasContMajor() && !link->isCont() && !ignoreRedLink) {
    3765     16855430 :                 if (!determinedFoePresence && (canBrake || !yellow)) {
    3766     15910428 :                     vSafe = dpi.myVLinkWait;
    3767     15910428 :                     myHaveToWaitOnNextLink = true;
    3768              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3769              :                     if (DEBUG_COND) {
    3770              :                         std::cout << SIMTIME << " veh=" << getID() << " haveToWait (minor)\n";
    3771              :                     }
    3772              : #endif
    3773     15910428 :                     break;
    3774              :                 } else {
    3775              :                     // past the point of no return. we need to drive fast enough
    3776              :                     // to make it across the link. However, minor slowdowns
    3777              :                     // should be permissible to follow leading traffic safely
    3778              :                     // basically, this code prevents dawdling
    3779              :                     // (it's harder to do this later using
    3780              :                     // SUMO_ATTR_JM_SIGMA_MINOR because we don't know whether the
    3781              :                     // vehicle is already too close to stop at that part of the code)
    3782              :                     //
    3783              :                     // XXX: There is a problem in subsecond simulation: If we cannot
    3784              :                     // make it across the minor link in one step, new traffic
    3785              :                     // could appear on a major foe link and cause a collision. Refs. #1845, #2123
    3786       945002 :                     vSafeMinDist = dpi.myDistance; // distance that must be covered
    3787       945002 :                     if (MSGlobals::gSemiImplicitEulerUpdate) {
    3788      1725004 :                         vSafeMin = MIN3((double)DIST2SPEED(vSafeMinDist + POSITION_EPS), dpi.myVLinkPass, getCarFollowModel().maxNextSafeMin(getSpeed(), this));
    3789              :                     } else {
    3790       165000 :                         vSafeMin = MIN3((double)DIST2SPEED(2 * vSafeMinDist + NUMERICAL_EPS) - getSpeed(), dpi.myVLinkPass, getCarFollowModel().maxNextSafeMin(getSpeed(), this));
    3791              :                     }
    3792              :                     canBrakeVSafeMin = canBrake;
    3793              : #ifdef DEBUG_EXEC_MOVE
    3794              :                     if (DEBUG_COND) {
    3795              :                         std::cout << "     vSafeMin=" << vSafeMin << " vSafeMinDist=" << vSafeMinDist << " canBrake=" << canBrake << "\n";
    3796              :                     }
    3797              : #endif
    3798              :                 }
    3799              :             }
    3800              :             // have waited; may pass if opened...
    3801    604482132 :             if (opened) {
    3802    599219890 :                 vSafe = dpi.myVLinkPass;
    3803    599219890 :                 if (vSafe < getCarFollowModel().getMaxDecel() && vSafe <= dpi.myVLinkWait && vSafe < getCarFollowModel().maxNextSpeed(getSpeed(), this)) {
    3804              :                     // this vehicle is probably not gonna drive across the next junction (heuristic)
    3805     53110970 :                     myHaveToWaitOnNextLink = true;
    3806              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3807              :                     if (DEBUG_COND) {
    3808              :                         std::cout << SIMTIME << " veh=" << getID() << " haveToWait (very slow)\n";
    3809              :                     }
    3810              : #endif
    3811              :                 }
    3812    599219890 :                 if (link->mustStop() && determinedFoePresence && myHaveStoppedFor == nullptr) {
    3813        19918 :                     myHaveStoppedFor = link;
    3814              :                 }
    3815      5262242 :             } else if (link->getState() == LINKSTATE_ZIPPER) {
    3816      1182132 :                 vSafeZipper = MIN2(vSafeZipper,
    3817      1182132 :                                    link->getZipperSpeed(this, dpi.myDistance, dpi.myVLinkPass, dpi.myArrivalTime, &collectFoes));
    3818              :             } else if (!canBrake
    3819              :                        // always brake hard for traffic lights (since an emergency stop is necessary anyway)
    3820         1736 :                        && link->getTLLogic() == nullptr
    3821              :                        // cannot brake even with emergency deceleration
    3822      4080990 :                        && dpi.myDistance < getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getEmergencyDecel(), 0.)) {
    3823              : #ifdef DEBUG_EXEC_MOVE
    3824              :                 if (DEBUG_COND) {
    3825              :                     std::cout << SIMTIME << " too fast to brake for closed link\n";
    3826              :                 }
    3827              : #endif
    3828          236 :                 vSafe = dpi.myVLinkPass;
    3829              :             } else {
    3830      4079874 :                 vSafe = dpi.myVLinkWait;
    3831      4079874 :                 myHaveToWaitOnNextLink = true;
    3832              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3833              :                 if (DEBUG_COND) {
    3834              :                     std::cout << SIMTIME << " veh=" << getID() << " haveToWait (closed)\n";
    3835              :                 }
    3836              : #endif
    3837              : #ifdef DEBUG_EXEC_MOVE
    3838              :                 if (DEBUG_COND) {
    3839              :                     std::cout << SIMTIME << " braking for closed link=" << link->getViaLaneOrLane()->getID() << "\n";
    3840              :                 }
    3841              : #endif
    3842      4079874 :                 break;
    3843              :             }
    3844    620392560 :         } else {
    3845    419731255 :             if (link != nullptr && link->getInternalLaneBefore() != nullptr && myLane->isInternal() && link->getJunction() == myLane->getEdge().getToJunction()) {
    3846              :                 // blocked on the junction. yield request so other vehicles may
    3847              :                 // become junction leader
    3848              : #ifdef DEBUG_EXEC_MOVE
    3849              :                 if (DEBUG_COND) {
    3850              :                     std::cout << SIMTIME << " resetting junctionEntryTime at junction '" << link->getJunction()->getID() << "' beause of non-request exitLink\n";
    3851              :                 }
    3852              : #endif
    3853       243486 :                 myJunctionEntryTime = SUMOTime_MAX;
    3854       243486 :                 myJunctionConflictEntryTime = SUMOTime_MAX;
    3855              :             }
    3856              :             // we have: i->link == 0 || !i->setRequest
    3857    419731255 :             vSafe = dpi.myVLinkWait;
    3858    419731255 :             if (link != nullptr || myStopDist < (myLane->getLength() - getPositionOnLane())) {
    3859     98534516 :                 if (vSafe < getSpeed()) {
    3860     14866912 :                     myHaveToWaitOnNextLink = true;
    3861              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3862              :                     if (DEBUG_COND) {
    3863              :                         std::cout << SIMTIME << " veh=" << getID() << " haveToWait (no request, braking) vSafe=" << vSafe << "\n";
    3864              :                     }
    3865              : #endif
    3866     83667604 :                 } else if (vSafe < SUMO_const_haltingSpeed) {
    3867     57656885 :                     myHaveToWaitOnNextLink = true;
    3868              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3869              :                     if (DEBUG_COND) {
    3870              :                         std::cout << SIMTIME << " veh=" << getID() << " haveToWait (no request, stopping)\n";
    3871              :                     }
    3872              : #endif
    3873              :                 }
    3874              :             }
    3875    326233917 :             if (link == nullptr && myLFLinkLanes.size() == 1
    3876    265874045 :                     && getBestLanesContinuation().size() > 1
    3877      1088435 :                     && getBestLanesContinuation()[1]->hadPermissionChanges()
    3878    419868026 :                     && myLane->getFirstAnyVehicle() == this) {
    3879              :                 // temporal lane closing without notification, visible to the
    3880              :                 // vehicle at the front of the queue
    3881        34547 :                 updateBestLanes(true);
    3882              :                 //std::cout << SIMTIME << " veh=" << getID() << " updated bestLanes=" << toString(getBestLanesContinuation()) << "\n";
    3883              :             }
    3884              :             break;
    3885              :         }
    3886              :     }
    3887              : 
    3888              : //#ifdef DEBUG_EXEC_MOVE
    3889              : //    if (DEBUG_COND) {
    3890              : //        std::cout << "\nvCurrent = " << toString(getSpeed(), 24) << "" << std::endl;
    3891              : //        std::cout << "vSafe = " << toString(vSafe, 24) << "" << std::endl;
    3892              : //        std::cout << "vSafeMin = " << toString(vSafeMin, 24) << "" << std::endl;
    3893              : //        std::cout << "vSafeMinDist = " << toString(vSafeMinDist, 24) << "" << std::endl;
    3894              : //
    3895              : //        double gap = getLeader().second;
    3896              : //        std::cout << "gap = " << toString(gap, 24) << std::endl;
    3897              : //        std::cout << "vSafeStoppedLeader = " << toString(getCarFollowModel().stopSpeed(this, getSpeed(), gap, MSCFModel::CalcReason::FUTURE), 24)
    3898              : //                << "\n" << std::endl;
    3899              : //    }
    3900              : //#endif
    3901              : 
    3902    608595485 :     if ((MSGlobals::gSemiImplicitEulerUpdate && vSafe + NUMERICAL_EPS < vSafeMin)
    3903    608387435 :             || (!MSGlobals::gSemiImplicitEulerUpdate && (vSafe + NUMERICAL_EPS < vSafeMin && vSafeMin != 0))) { // this might be good for the euler case as well
    3904              :         // XXX: (Leo) This often called stopSpeed with vSafeMinDist==0 (for the ballistic update), since vSafe can become negative
    3905              :         //      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
    3906              : #ifdef DEBUG_EXEC_MOVE
    3907              :         if (DEBUG_COND) {
    3908              :             std::cout << "vSafeMin Problem? vSafe=" << vSafe << " vSafeMin=" << vSafeMin << " vSafeMinDist=" << vSafeMinDist << std::endl;
    3909              :         }
    3910              : #endif
    3911       247910 :         if (canBrakeVSafeMin && vSafe < getSpeed()) {
    3912              :             // cannot drive across a link so we need to stop before it
    3913       125490 :             vSafe = MIN2(vSafe, MAX2(getCarFollowModel().minNextSpeed(getSpeed(), this),
    3914        62745 :                                      getCarFollowModel().stopSpeed(this, getSpeed(), vSafeMinDist)));
    3915        62745 :             vSafeMin = 0;
    3916        62745 :             myHaveToWaitOnNextLink = true;
    3917              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3918              :             if (DEBUG_COND) {
    3919              :                 std::cout << SIMTIME << " veh=" << getID() << " haveToWait (vSafe=" << vSafe << " < vSafeMin=" << vSafeMin << ")\n";
    3920              :             }
    3921              : #endif
    3922              :         } else {
    3923              :             // if the link is yellow or visibility distance is large
    3924              :             // then we might not make it across the link in one step anyway..
    3925              :             // Possibly, the lane after the intersection has a lower speed limit so
    3926              :             // we really need to drive slower already
    3927              :             // -> keep driving without dawdling
    3928       185165 :             vSafeMin = vSafe;
    3929              :         }
    3930              :     }
    3931              : 
    3932              :     // vehicles inside a roundabout should maintain their requests
    3933    608595485 :     if (myLane->getEdge().isRoundabout()) {
    3934      2670824 :         myHaveToWaitOnNextLink = false;
    3935              :     }
    3936              : 
    3937    608595485 :     vSafe = MIN2(vSafe, vSafeZipper);
    3938    608595485 : }
    3939              : 
    3940              : 
    3941              : double
    3942    675837666 : MSVehicle::processTraCISpeedControl(double vSafe, double vNext) {
    3943    675837666 :     if (myInfluencer != nullptr) {
    3944       502067 :         myInfluencer->setOriginalSpeed(vNext);
    3945              : #ifdef DEBUG_TRACI
    3946              :         if DEBUG_COND2(this) {
    3947              :             std::cout << SIMTIME << " MSVehicle::processTraCISpeedControl() for vehicle '" << getID() << "'"
    3948              :                       << " vSafe=" << vSafe << " (init)vNext=" << vNext << " keepStopping=" << keepStopping();
    3949              :         }
    3950              : #endif
    3951       502067 :         if (myInfluencer->isRemoteControlled()) {
    3952         7752 :             vNext = myInfluencer->implicitSpeedRemote(this, myState.mySpeed);
    3953              :         }
    3954       502067 :         const double vMax = getVehicleType().getCarFollowModel().maxNextSpeed(myState.mySpeed, this);
    3955       502067 :         double vMin = getVehicleType().getCarFollowModel().minNextSpeed(myState.mySpeed, this);
    3956       502067 :         if (MSGlobals::gSemiImplicitEulerUpdate) {
    3957              :             vMin = MAX2(0., vMin);
    3958              :         }
    3959       502067 :         vNext = myInfluencer->influenceSpeed(MSNet::getInstance()->getCurrentTimeStep(), vNext, vSafe, vMin, vMax);
    3960       502067 :         if (keepStopping() && myStops.front().getSpeed() == 0) {
    3961              :             // avoid driving while stopped (unless it's actually a waypoint
    3962         3746 :             vNext = myInfluencer->getOriginalSpeed();
    3963              :         }
    3964              : #ifdef DEBUG_TRACI
    3965              :         if DEBUG_COND2(this) {
    3966              :             std::cout << " (processed)vNext=" << vNext << std::endl;
    3967              :         }
    3968              : #endif
    3969              :     }
    3970    675837666 :     return vNext;
    3971              : }
    3972              : 
    3973              : 
    3974              : void
    3975     71516924 : MSVehicle::removePassedDriveItems() {
    3976              : #ifdef DEBUG_ACTIONSTEPS
    3977              :     if (DEBUG_COND) {
    3978              :         std::cout << SIMTIME << " veh=" << getID() << " removePassedDriveItems()\n"
    3979              :                   << "    Current items: ";
    3980              :         for (auto& j : myLFLinkLanes) {
    3981              :             if (j.myLink == 0) {
    3982              :                 std::cout << "\n    Stop at distance " << j.myDistance;
    3983              :             } else {
    3984              :                 const MSLane* to = j.myLink->getViaLaneOrLane();
    3985              :                 const MSLane* from = j.myLink->getLaneBefore();
    3986              :                 std::cout << "\n    Link at distance " << j.myDistance << ": '"
    3987              :                           << (from == 0 ? "NONE" : from->getID()) << "' -> '" << (to == 0 ? "NONE" : to->getID()) << "'";
    3988              :             }
    3989              :         }
    3990              :         std::cout << "\n    myNextDriveItem: ";
    3991              :         if (myLFLinkLanes.size() != 0) {
    3992              :             if (myNextDriveItem->myLink == 0) {
    3993              :                 std::cout << "\n    Stop at distance " << myNextDriveItem->myDistance;
    3994              :             } else {
    3995              :                 const MSLane* to = myNextDriveItem->myLink->getViaLaneOrLane();
    3996              :                 const MSLane* from = myNextDriveItem->myLink->getLaneBefore();
    3997              :                 std::cout << "\n    Link at distance " << myNextDriveItem->myDistance << ": '"
    3998              :                           << (from == 0 ? "NONE" : from->getID()) << "' -> '" << (to == 0 ? "NONE" : to->getID()) << "'";
    3999              :             }
    4000              :         }
    4001              :         std::cout << std::endl;
    4002              :     }
    4003              : #endif
    4004     71843099 :     for (auto j = myLFLinkLanes.begin(); j != myNextDriveItem; ++j) {
    4005              : #ifdef DEBUG_ACTIONSTEPS
    4006              :         if (DEBUG_COND) {
    4007              :             std::cout << "    Removing item: ";
    4008              :             if (j->myLink == 0) {
    4009              :                 std::cout << "Stop at distance " << j->myDistance;
    4010              :             } else {
    4011              :                 const MSLane* to = j->myLink->getViaLaneOrLane();
    4012              :                 const MSLane* from = j->myLink->getLaneBefore();
    4013              :                 std::cout << "Link at distance " << j->myDistance << ": '"
    4014              :                           << (from == 0 ? "NONE" : from->getID()) << "' -> '" << (to == 0 ? "NONE" : to->getID()) << "'";
    4015              :             }
    4016              :             std::cout << std::endl;
    4017              :         }
    4018              : #endif
    4019       326175 :         if (j->myLink != nullptr) {
    4020       326107 :             j->myLink->removeApproaching(this);
    4021              :         }
    4022              :     }
    4023     71516924 :     myLFLinkLanes.erase(myLFLinkLanes.begin(), myNextDriveItem);
    4024     71516924 :     myNextDriveItem = myLFLinkLanes.begin();
    4025     71516924 : }
    4026              : 
    4027              : 
    4028              : void
    4029      1113526 : MSVehicle::updateDriveItems() {
    4030              : #ifdef DEBUG_ACTIONSTEPS
    4031              :     if (DEBUG_COND) {
    4032              :         std::cout << SIMTIME << " updateDriveItems(), veh='" << getID() << "' (lane: '" << getLane()->getID() << "')\nCurrent drive items:" << std::endl;
    4033              :         for (const auto& dpi : myLFLinkLanes) {
    4034              :             std::cout
    4035              :                     << " vPass=" << dpi.myVLinkPass
    4036              :                     << " vWait=" << dpi.myVLinkWait
    4037              :                     << " linkLane=" << (dpi.myLink == 0 ? "NULL" : dpi.myLink->getViaLaneOrLane()->getID())
    4038              :                     << " request=" << dpi.mySetRequest
    4039              :                     << "\n";
    4040              :         }
    4041              :         std::cout << " myNextDriveItem's linked lane: " << (myNextDriveItem->myLink == 0 ? "NULL" : myNextDriveItem->myLink->getViaLaneOrLane()->getID()) << std::endl;
    4042              :     }
    4043              : #endif
    4044      1113526 :     if (myLFLinkLanes.size() == 0) {
    4045              :         // nothing to update
    4046              :         return;
    4047              :     }
    4048              :     const MSLink* nextPlannedLink = nullptr;
    4049              : //    auto i = myLFLinkLanes.begin();
    4050      1113526 :     auto i = myNextDriveItem;
    4051      2227018 :     while (i != myLFLinkLanes.end() && nextPlannedLink == nullptr) {
    4052      1113492 :         nextPlannedLink = i->myLink;
    4053              :         ++i;
    4054              :     }
    4055              : 
    4056      1113526 :     if (nextPlannedLink == nullptr) {
    4057              :         // No link for upcoming item -> no need for an update
    4058              : #ifdef DEBUG_ACTIONSTEPS
    4059              :         if (DEBUG_COND) {
    4060              :             std::cout << "Found no link-related drive item." << std::endl;
    4061              :         }
    4062              : #endif
    4063              :         return;
    4064              :     }
    4065              : 
    4066       545474 :     if (getLane() == nextPlannedLink->getLaneBefore()) {
    4067              :         // Current lane approaches the stored next link, i.e. no LC happend and no update is required.
    4068              : #ifdef DEBUG_ACTIONSTEPS
    4069              :         if (DEBUG_COND) {
    4070              :             std::cout << "Continuing on planned lane sequence, no update required." << std::endl;
    4071              :         }
    4072              : #endif
    4073              :         return;
    4074              :     }
    4075              :     // Lane must have been changed, determine the change direction
    4076       535646 :     const MSLink* parallelLink = nextPlannedLink->getParallelLink(1);
    4077       535646 :     if (parallelLink != nullptr && parallelLink->getLaneBefore() == getLane()) {
    4078              :         // lcDir = 1;
    4079              :     } else {
    4080       266568 :         parallelLink = nextPlannedLink->getParallelLink(-1);
    4081       266568 :         if (parallelLink != nullptr && parallelLink->getLaneBefore() == getLane()) {
    4082              :             // lcDir = -1;
    4083              :         } else {
    4084              :             // If the vehicle's current lane is not the approaching lane for the next
    4085              :             // drive process item's link, it is expected to lead to a parallel link,
    4086              :             // XXX: What if the lc was an overtaking maneuver and there is no upcoming link?
    4087              :             //      Then a stop item should be scheduled! -> TODO!
    4088              :             //assert(false);
    4089        72127 :             return;
    4090              :         }
    4091              :     }
    4092              : #ifdef DEBUG_ACTIONSTEPS
    4093              :     if (DEBUG_COND) {
    4094              :         std::cout << "Changed lane. Drive items will be updated along the current lane continuation." << std::endl;
    4095              :     }
    4096              : #endif
    4097              :     // Trace link sequence along current best lanes and transfer drive items to the corresponding links
    4098              : //        DriveItemVector::iterator driveItemIt = myLFLinkLanes.begin();
    4099       463519 :     DriveItemVector::iterator driveItemIt = myNextDriveItem;
    4100              :     // In the loop below, lane holds the currently considered lane on the vehicles continuation (including internal lanes)
    4101       463519 :     const MSLane* lane = myLane;
    4102              :     assert(myLane == parallelLink->getLaneBefore());
    4103              :     // *lit is a pointer to the next lane in best continuations for the current lane (always non-internal)
    4104       463519 :     std::vector<MSLane*>::const_iterator bestLaneIt = getBestLanesContinuation().begin() + 1;
    4105              :     // Pointer to the new link for the current drive process item
    4106              :     MSLink* newLink = nullptr;
    4107      1736187 :     while (driveItemIt != myLFLinkLanes.end()) {
    4108      1301857 :         if (driveItemIt->myLink == nullptr) {
    4109              :             // Items not related to a specific link are not updated
    4110              :             // (XXX: when a stop item corresponded to a dead end, which is overcome by the LC that made
    4111              :             //       the update necessary, this may slow down the vehicle's continuation on the new lane...)
    4112              :             ++driveItemIt;
    4113       158757 :             continue;
    4114              :         }
    4115              :         // Continuation links for current best lanes are less than for the former drive items (myLFLinkLanes)
    4116              :         // We just remove the leftover link-items, as they cannot be mapped to new links.
    4117      1143100 :         if (bestLaneIt == getBestLanesContinuation().end()) {
    4118              : #ifdef DEBUG_ACTIONSTEPS
    4119              :             if (DEBUG_COND) {
    4120              :                 std::cout << "Reached end of the new continuation sequence. Erasing leftover link-items." << std::endl;
    4121              :             }
    4122              : #endif
    4123        92037 :             while (driveItemIt != myLFLinkLanes.end()) {
    4124        62848 :                 if (driveItemIt->myLink == nullptr) {
    4125              :                     ++driveItemIt;
    4126        14345 :                     continue;
    4127              :                 } else {
    4128        48503 :                     driveItemIt->myLink->removeApproaching(this);
    4129              :                     driveItemIt = myLFLinkLanes.erase(driveItemIt);
    4130              :                 }
    4131              :             }
    4132              :             break;
    4133              :         }
    4134              :         // Do the actual link-remapping for the item. And un/register approaching information on the corresponding links
    4135      1113911 :         const MSLane* const target = *bestLaneIt;
    4136              :         assert(!target->isInternal());
    4137              :         newLink = nullptr;
    4138      1233885 :         for (MSLink* const link : lane->getLinkCont()) {
    4139      1233885 :             if (link->getLane() == target) {
    4140              :                 newLink = link;
    4141              :                 break;
    4142              :             }
    4143              :         }
    4144              : 
    4145      1113911 :         if (newLink == driveItemIt->myLink) {
    4146              :             // new continuation merged into previous - stop update
    4147              : #ifdef DEBUG_ACTIONSTEPS
    4148              :             if (DEBUG_COND) {
    4149              :                 std::cout << "Old and new continuation sequences merge at link\n"
    4150              :                           << "'" << newLink->getLaneBefore()->getID() << "'->'" << newLink->getViaLaneOrLane()->getID() << "'"
    4151              :                           << "\nNo update beyond merge required." << std::endl;
    4152              :             }
    4153              : #endif
    4154              :             break;
    4155              :         }
    4156              : 
    4157              : #ifdef DEBUG_ACTIONSTEPS
    4158              :         if (DEBUG_COND) {
    4159              :             std::cout << "lane=" << lane->getID() << "\nUpdating link\n    '" << driveItemIt->myLink->getLaneBefore()->getID() << "'->'" << driveItemIt->myLink->getViaLaneOrLane()->getID() << "'"
    4160              :                       << "==> " << "'" << newLink->getLaneBefore()->getID() << "'->'" << newLink->getViaLaneOrLane()->getID() << "'" << std::endl;
    4161              :         }
    4162              : #endif
    4163      1113911 :         newLink->setApproaching(this, driveItemIt->myLink->getApproaching(this));
    4164      1113911 :         driveItemIt->myLink->removeApproaching(this);
    4165      1113911 :         driveItemIt->myLink = newLink;
    4166              :         lane = newLink->getViaLaneOrLane();
    4167              :         ++driveItemIt;
    4168      1113911 :         if (!lane->isInternal()) {
    4169              :             ++bestLaneIt;
    4170              :         }
    4171              :     }
    4172              : #ifdef DEBUG_ACTIONSTEPS
    4173              :     if (DEBUG_COND) {
    4174              :         std::cout << "Updated drive items:" << std::endl;
    4175              :         for (const auto& dpi : myLFLinkLanes) {
    4176              :             std::cout
    4177              :                     << " vPass=" << dpi.myVLinkPass
    4178              :                     << " vWait=" << dpi.myVLinkWait
    4179              :                     << " linkLane=" << (dpi.myLink == 0 ? "NULL" : dpi.myLink->getViaLaneOrLane()->getID())
    4180              :                     << " request=" << dpi.mySetRequest
    4181              :                     << "\n";
    4182              :         }
    4183              :     }
    4184              : #endif
    4185              : }
    4186              : 
    4187              : 
    4188              : void
    4189    675837666 : MSVehicle::setBrakingSignals(double vNext) {
    4190              :     // To avoid casual blinking brake lights at high speeds due to dawdling of the
    4191              :     // leading vehicle, we don't show brake lights when the deceleration could be caused
    4192              :     // by frictional forces and air resistance (i.e. proportional to v^2, coefficient could be adapted further)
    4193    675837666 :     double pseudoFriction = (0.05 +  0.005 * getSpeed()) * getSpeed();
    4194    675837666 :     bool brakelightsOn = vNext < getSpeed() - ACCEL2SPEED(pseudoFriction);
    4195              : 
    4196    675837666 :     if (vNext <= SUMO_const_haltingSpeed) {
    4197              :         brakelightsOn = true;
    4198              :     }
    4199    675837666 :     if (brakelightsOn && !isStopped()) {
    4200              :         switchOnSignal(VEH_SIGNAL_BRAKELIGHT);
    4201              :     } else {
    4202              :         switchOffSignal(VEH_SIGNAL_BRAKELIGHT);
    4203              :     }
    4204    675837666 : }
    4205              : 
    4206              : 
    4207              : void
    4208    675941764 : MSVehicle::updateWaitingTime(double vNext) {
    4209    675941764 :     if (vNext <= SUMO_const_haltingSpeed && (!isStopped() || isIdling()) && myAcceleration <= accelThresholdForWaiting())  {
    4210     83723271 :         myWaitingTime += DELTA_T;
    4211     83723271 :         myWaitingTimeCollector.passTime(DELTA_T, true);
    4212              :     } else {
    4213    592218493 :         myWaitingTime = 0;
    4214    592218493 :         myWaitingTimeCollector.passTime(DELTA_T, false);
    4215    592218493 :         if (hasInfluencer()) {
    4216       276628 :             getInfluencer().setExtraImpatience(0);
    4217              :         }
    4218              :     }
    4219    675941764 : }
    4220              : 
    4221              : 
    4222              : void
    4223    675837484 : MSVehicle::updateTimeLoss(double vNext) {
    4224              :     // update time loss (depends on the updated edge)
    4225    675837484 :     if (!isStopped()) {
    4226    662206360 :         const double vmax = myLane->getVehicleMaxSpeed(this);
    4227    662206360 :         if (vmax > 0) {
    4228    662198976 :             myTimeLoss += TS * (vmax - vNext) / vmax;
    4229              :         }
    4230              :     }
    4231    675837484 : }
    4232              : 
    4233              : 
    4234              : double
    4235   1485565965 : MSVehicle::checkReversal(bool& canReverse, double speedThreshold, double seen) const {
    4236     49696151 :     const bool stopOk = (myStops.empty() || myStops.front().edge != myCurrEdge
    4237   1508237567 :                          || (myStops.front().getSpeed() > 0 && myState.myPos > myStops.front().pars.endPos - 2 * POSITION_EPS));
    4238              : #ifdef DEBUG_REVERSE_BIDI
    4239              :     if (DEBUG_COND) std::cout << SIMTIME  << " checkReversal lane=" << myLane->getID()
    4240              :                                   << " pos=" << myState.myPos
    4241              :                                   << " speed=" << std::setprecision(6) << getPreviousSpeed() << std::setprecision(gPrecision)
    4242              :                                   << " speedThreshold=" << speedThreshold
    4243              :                                   << " seen=" << seen
    4244              :                                   << " isRail=" << isRail()
    4245              :                                   << " speedOk=" << (getPreviousSpeed() <= speedThreshold)
    4246              :                                   << " posOK=" << (myState.myPos <= myLane->getLength())
    4247              :                                   << " normal=" << !myLane->isInternal()
    4248              :                                   << " routeOK=" << ((myCurrEdge + 1) != myRoute->end())
    4249              :                                   << " bidi=" << (myLane->getEdge().getBidiEdge() == *(myCurrEdge + 1))
    4250              :                                   << " stopOk=" << stopOk
    4251              :                                   << "\n";
    4252              : #endif
    4253   1485565965 :     if ((getVClass() & SVC_RAIL_CLASSES) != 0
    4254      6621971 :             && getPreviousSpeed() <= speedThreshold
    4255      5649856 :             && myState.myPos <= myLane->getLength()
    4256      5648863 :             && !myLane->isInternal()
    4257      5583628 :             && (myCurrEdge + 1) != myRoute->end()
    4258      5494826 :             && myLane->getEdge().getBidiEdge() == *(myCurrEdge + 1)
    4259              :             // ensure there are no further stops on this edge
    4260   1486412561 :             && stopOk
    4261              :        ) {
    4262              :         //if (isSelected()) std::cout << "   check1 passed\n";
    4263              : 
    4264              :         // ensure that the vehicle is fully on bidi edges that allow reversal
    4265       177786 :         const int neededFutureRoute = 1 + (int)(MSGlobals::gUsingInternalLanes
    4266              :                                                 ? myFurtherLanes.size()
    4267          504 :                                                 : ceil((double)myFurtherLanes.size() / 2.0));
    4268       177786 :         const int remainingRoute = int(myRoute->end() - myCurrEdge) - 1;
    4269       177786 :         if (remainingRoute < neededFutureRoute) {
    4270              : #ifdef DEBUG_REVERSE_BIDI
    4271              :             if (DEBUG_COND) {
    4272              :                 std::cout << "    fail: remainingEdges=" << ((int)(myRoute->end() - myCurrEdge)) << " further=" << myFurtherLanes.size() << "\n";
    4273              :             }
    4274              : #endif
    4275         3567 :             return getMaxSpeed();
    4276              :         }
    4277              :         //if (isSelected()) std::cout << "   check2 passed\n";
    4278              : 
    4279              :         // ensure that the turn-around connection exists from the current edge to its bidi-edge
    4280       174219 :         const MSEdgeVector& succ = myLane->getEdge().getSuccessors();
    4281       174219 :         if (std::find(succ.begin(), succ.end(), myLane->getEdge().getBidiEdge()) == succ.end()) {
    4282              : #ifdef DEBUG_REVERSE_BIDI
    4283              :             if (DEBUG_COND) {
    4284              :                 std::cout << "    noTurn (bidi=" << myLane->getEdge().getBidiEdge()->getID() << " succ=" << toString(succ) << "\n";
    4285              :             }
    4286              : #endif
    4287          909 :             return getMaxSpeed();
    4288              :         }
    4289              :         //if (isSelected()) std::cout << "   check3 passed\n";
    4290              : 
    4291              :         // ensure that the vehicle front will not move past a stop on the bidi edge of the current edge
    4292       173310 :         if (!myStops.empty() && myStops.front().edge == (myCurrEdge + 1)) {
    4293       160006 :             const double stopPos = myStops.front().getEndPos(*this);
    4294       160006 :             const double brakeDist = getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), 0);
    4295       160006 :             const double newPos = myLane->getLength() - (getBackPositionOnLane() + brakeDist);
    4296       160006 :             if (newPos > stopPos) {
    4297              : #ifdef DEBUG_REVERSE_BIDI
    4298              :                 if (DEBUG_COND) {
    4299              :                     std::cout << "    reversal would go past stop on " << myLane->getBidiLane()->getID() << "\n";
    4300              :                 }
    4301              : #endif
    4302       158332 :                 if (seen > MAX2(brakeDist, 1.0)) {
    4303       157202 :                     return getMaxSpeed();
    4304              :                 } else {
    4305              : #ifdef DEBUG_REVERSE_BIDI
    4306              :                     if (DEBUG_COND) {
    4307              :                         std::cout << "    train is too long, skipping stop at " << stopPos << " cannot be avoided\n";
    4308              :                     }
    4309              : #endif
    4310              :                 }
    4311              :             }
    4312              :         }
    4313              :         //if (isSelected()) std::cout << "   check4 passed\n";
    4314              : 
    4315              :         // ensure that bidi-edges exist for all further edges
    4316              :         // and that no stops will be skipped when reversing
    4317              :         // and that the train will not be on top of a red rail signal after reversal
    4318        16108 :         const MSLane* bidi = myLane->getBidiLane();
    4319              :         int view = 2;
    4320        32828 :         for (MSLane* further : myFurtherLanes) {
    4321        18277 :             if (!further->getEdge().isInternal()) {
    4322         9709 :                 if (further->getEdge().getBidiEdge() != *(myCurrEdge + view)) {
    4323              : #ifdef DEBUG_REVERSE_BIDI
    4324              :                     if (DEBUG_COND) {
    4325              :                         std::cout << "    noBidi view=" << view << " further=" << further->getID() << " furtherBidi=" << Named::getIDSecure(further->getEdge().getBidiEdge()) << " future=" << (*(myCurrEdge + view))->getID() << "\n";
    4326              :                     }
    4327              : #endif
    4328         1398 :                     return getMaxSpeed();
    4329              :                 }
    4330         8311 :                 const MSLane* nextBidi = further->getBidiLane();
    4331         8311 :                 const MSLink* toNext = bidi->getLinkTo(nextBidi);
    4332         8311 :                 if (toNext == nullptr) {
    4333              :                     // can only happen if the route is invalid
    4334            0 :                     return getMaxSpeed();
    4335              :                 }
    4336         8311 :                 if (toNext->haveRed()) {
    4337              : #ifdef DEBUG_REVERSE_BIDI
    4338              :                     if (DEBUG_COND) {
    4339              :                         std::cout << "    do not reverse on a red signal\n";
    4340              :                     }
    4341              : #endif
    4342            0 :                     return getMaxSpeed();
    4343              :                 }
    4344              :                 bidi = nextBidi;
    4345         8311 :                 if (!myStops.empty() && myStops.front().edge == (myCurrEdge + view)) {
    4346          453 :                     const double brakeDist = getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), 0);
    4347          453 :                     const double stopPos = myStops.front().getEndPos(*this);
    4348          453 :                     const double newPos = further->getLength() - (getBackPositionOnLane(further) + brakeDist);
    4349          453 :                     if (newPos > stopPos) {
    4350              : #ifdef DEBUG_REVERSE_BIDI
    4351              :                         if (DEBUG_COND) {
    4352              :                             std::cout << "    reversal would go past stop on further-opposite lane " << further->getBidiLane()->getID() << "\n";
    4353              :                         }
    4354              : #endif
    4355          171 :                         if (seen > MAX2(brakeDist, 1.0)) {
    4356          159 :                             canReverse = false;
    4357          159 :                             return getMaxSpeed();
    4358              :                         } else {
    4359              : #ifdef DEBUG_REVERSE_BIDI
    4360              :                             if (DEBUG_COND) {
    4361              :                                 std::cout << "    train is too long, skipping stop at " << stopPos << " cannot be avoided\n";
    4362              :                             }
    4363              : #endif
    4364              :                         }
    4365              :                     }
    4366              :                 }
    4367         8152 :                 view++;
    4368              :             }
    4369              :         }
    4370              :         // reverse as soon as comfortably possible
    4371        14551 :         const double vMinComfortable = getCarFollowModel().minNextSpeed(getSpeed(), this);
    4372              : #ifdef DEBUG_REVERSE_BIDI
    4373              :         if (DEBUG_COND) {
    4374              :             std::cout << SIMTIME << " seen=" << seen  << " vReverseOK=" << vMinComfortable << "\n";
    4375              :         }
    4376              : #endif
    4377        14551 :         canReverse = true;
    4378        14551 :         return vMinComfortable;
    4379              :     }
    4380   1485388179 :     return getMaxSpeed();
    4381              : }
    4382              : 
    4383              : 
    4384              : void
    4385    676051550 : MSVehicle::processLaneAdvances(std::vector<MSLane*>& passedLanes, std::string& emergencyReason) {
    4386    691562953 :     for (std::vector<MSLane*>::reverse_iterator i = myFurtherLanes.rbegin(); i != myFurtherLanes.rend(); ++i) {
    4387     15511403 :         passedLanes.push_back(*i);
    4388              :     }
    4389    676051550 :     if (passedLanes.size() == 0 || passedLanes.back() != myLane) {
    4390    676051550 :         passedLanes.push_back(myLane);
    4391              :     }
    4392              :     // let trains reverse direction
    4393    676051550 :     bool reverseTrain = false;
    4394    676051550 :     checkReversal(reverseTrain);
    4395    676051550 :     if (reverseTrain) {
    4396              :         // Train is 'reversing' so toggle the logical state
    4397          772 :         myAmReversed = !myAmReversed;
    4398              :         // add some slack to ensure that the back of train does appear looped
    4399          772 :         myState.myPos += 2 * (myLane->getLength() - myState.myPos) + myType->getLength() + NUMERICAL_EPS;
    4400          772 :         myState.mySpeed = 0;
    4401              : #ifdef DEBUG_REVERSE_BIDI
    4402              :         if (DEBUG_COND) {
    4403              :             std::cout << SIMTIME << " reversing train=" << getID() << " newPos=" << myState.myPos << "\n";
    4404              :         }
    4405              : #endif
    4406              :     }
    4407              :     // move on lane(s)
    4408    676051550 :     if (myState.myPos > myLane->getLength()) {
    4409              :         // The vehicle has moved at least to the next lane (maybe it passed even more than one)
    4410     17907955 :         if (myCurrEdge != myRoute->end() - 1) {
    4411     15163437 :             MSLane* approachedLane = myLane;
    4412              :             // move the vehicle forward
    4413     15163437 :             myNextDriveItem = myLFLinkLanes.begin();
    4414     32908460 :             while (myNextDriveItem != myLFLinkLanes.end() && approachedLane != nullptr && myState.myPos > approachedLane->getLength()) {
    4415     17760016 :                 const MSLink* link = myNextDriveItem->myLink;
    4416     17760016 :                 const double linkDist = myNextDriveItem->myDistance;
    4417              :                 ++myNextDriveItem;
    4418              :                 // check whether the vehicle was allowed to enter lane
    4419              :                 //  otherwise it is decelerated and we do not need to test for it's
    4420              :                 //  approach on the following lanes when a lane changing is performed
    4421              :                 // proceed to the next lane
    4422     17760016 :                 if (approachedLane->mustCheckJunctionCollisions()) {
    4423              :                     // vehicle moves past approachedLane within a single step, collision checking must still be done
    4424        60626 :                     MSNet::getInstance()->getEdgeControl().checkCollisionForInactive(approachedLane);
    4425              :                 }
    4426     17760016 :                 if (link != nullptr) {
    4427     17757118 :                     if ((getVClass() & SVC_RAIL_CLASSES) != 0
    4428        39825 :                             && !myLane->isInternal()
    4429        21098 :                             && myLane->getBidiLane() != nullptr
    4430        11981 :                             && link->getLane()->getBidiLane() == myLane
    4431     17757887 :                             && !reverseTrain) {
    4432              :                         emergencyReason = " because it must reverse direction";
    4433              :                         approachedLane = nullptr;
    4434              :                         break;
    4435              :                     }
    4436     17757115 :                     if ((getVClass() & SVC_RAIL_CLASSES) != 0
    4437        39822 :                             && myState.myPos < myLane->getLength() + NUMERICAL_EPS
    4438     17757340 :                             && hasStops() && getNextStop().edge == myCurrEdge) {
    4439              :                         // avoid skipping stop due to numerical instability
    4440              :                         // this is a special case for rail vehicles because they
    4441              :                         // continue myLFLinkLanes past stops
    4442          197 :                         approachedLane = myLane;
    4443          197 :                         myState.myPos = myLane->getLength();
    4444          197 :                         break;
    4445              :                     }
    4446     17756918 :                     approachedLane = link->getViaLaneOrLane();
    4447     17756918 :                     if (myInfluencer == nullptr || myInfluencer->getEmergencyBrakeRedLight()) {
    4448     17755322 :                         bool beyondStopLine = linkDist < link->getLaneBefore()->getVehicleStopOffset(this);
    4449     17755322 :                         if (link->haveRed() && !ignoreRed(link, false) && !beyondStopLine && !reverseTrain) {
    4450              :                             emergencyReason = " because of a red traffic light";
    4451              :                             break;
    4452              :                         }
    4453              :                     }
    4454     17756864 :                     if (reverseTrain && approachedLane->isInternal()) {
    4455              :                         // avoid getting stuck on a slow turn-around internal lane
    4456          842 :                         myState.myPos += approachedLane->getLength();
    4457              :                     }
    4458         2898 :                 } else if (myState.myPos < myLane->getLength() + NUMERICAL_EPS) {
    4459              :                     // avoid warning due to numerical instability
    4460          165 :                     approachedLane = myLane;
    4461          165 :                     myState.myPos = myLane->getLength();
    4462         2733 :                 } else if (reverseTrain) {
    4463            0 :                     approachedLane = (*(myCurrEdge + 1))->getLanes()[0];
    4464            0 :                     link = myLane->getLinkTo(approachedLane);
    4465              :                     assert(link != 0);
    4466            0 :                     while (link->getViaLane() != nullptr) {
    4467            0 :                         link = link->getViaLane()->getLinkCont()[0];
    4468              :                     }
    4469              :                     --myNextDriveItem;
    4470              :                 } else {
    4471              :                     emergencyReason = " because there is no connection to the next edge";
    4472              :                     approachedLane = nullptr;
    4473              :                     break;
    4474              :                 }
    4475     17757029 :                 if (approachedLane != myLane && approachedLane != nullptr) {
    4476     17756864 :                     leaveLane(MSMoveReminder::NOTIFICATION_JUNCTION, approachedLane);
    4477     17756864 :                     myState.myPos -= myLane->getLength();
    4478              :                     assert(myState.myPos > 0);
    4479     17756864 :                     enterLaneAtMove(approachedLane);
    4480     17756864 :                     if (link->isEntryLink()) {
    4481      6820126 :                         myJunctionEntryTime = MSNet::getInstance()->getCurrentTimeStep();
    4482      6820126 :                         myJunctionEntryTimeNeverYield = myJunctionEntryTime;
    4483      6820126 :                         myHaveStoppedFor = nullptr;
    4484              :                     }
    4485     17756864 :                     if (link->isConflictEntryLink()) {
    4486      6819689 :                         myJunctionConflictEntryTime = MSNet::getInstance()->getCurrentTimeStep();
    4487              :                         // renew yielded request
    4488      6819689 :                         myJunctionEntryTime = myJunctionEntryTimeNeverYield;
    4489              :                     }
    4490     17756864 :                     if (link->isExitLink()) {
    4491              :                         // passed junction, reset for approaching the next one
    4492      6759884 :                         myJunctionEntryTime = SUMOTime_MAX;
    4493      6759884 :                         myJunctionEntryTimeNeverYield = SUMOTime_MAX;
    4494      6759884 :                         myJunctionConflictEntryTime = SUMOTime_MAX;
    4495              :                     }
    4496              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    4497              :                     if (DEBUG_COND) {
    4498              :                         std::cout << "Update junctionTimes link=" << link->getViaLaneOrLane()->getID()
    4499              :                                   << " entry=" << link->isEntryLink() << " conflict=" << link->isConflictEntryLink() << " exit=" << link->isExitLink()
    4500              :                                   << " ET=" << myJunctionEntryTime
    4501              :                                   << " ETN=" << myJunctionEntryTimeNeverYield
    4502              :                                   << " CET=" << myJunctionConflictEntryTime
    4503              :                                   << "\n";
    4504              :                     }
    4505              : #endif
    4506     17756864 :                     if (hasArrivedInternal()) {
    4507              :                         break;
    4508              :                     }
    4509     17745614 :                     if (myLaneChangeModel->isChangingLanes()) {
    4510         6570 :                         if (link->getDirection() == LinkDirection::LEFT || link->getDirection() == LinkDirection::RIGHT) {
    4511              :                             // abort lane change
    4512            0 :                             WRITE_WARNING("Vehicle '" + getID() + "' could not finish continuous lane change (turn lane) time=" +
    4513              :                                           time2string(MSNet::getInstance()->getCurrentTimeStep()) + ".");
    4514            0 :                             myLaneChangeModel->endLaneChangeManeuver();
    4515              :                         }
    4516              :                     }
    4517     17745614 :                     if (approachedLane->getEdge().isVaporizing()) {
    4518          756 :                         leaveLane(MSMoveReminder::NOTIFICATION_VAPORIZED_VAPORIZER);
    4519              :                         break;
    4520              :                     }
    4521     17744858 :                     passedLanes.push_back(approachedLane);
    4522              :                 }
    4523              :             }
    4524              :             // NOTE: Passed drive items will be erased in the next simstep's planMove()
    4525              : 
    4526              : #ifdef DEBUG_ACTIONSTEPS
    4527              :             if (DEBUG_COND && myNextDriveItem != myLFLinkLanes.begin()) {
    4528              :                 std::cout << "Updated drive items:" << std::endl;
    4529              :                 for (DriveItemVector::iterator i = myLFLinkLanes.begin(); i != myLFLinkLanes.end(); ++i) {
    4530              :                     std::cout
    4531              :                             << " vPass=" << (*i).myVLinkPass
    4532              :                             << " vWait=" << (*i).myVLinkWait
    4533              :                             << " linkLane=" << ((*i).myLink == 0 ? "NULL" : (*i).myLink->getViaLaneOrLane()->getID())
    4534              :                             << " request=" << (*i).mySetRequest
    4535              :                             << "\n";
    4536              :                 }
    4537              :             }
    4538              : #endif
    4539      2744518 :         } else if (!hasArrivedInternal() && myState.myPos < myLane->getLength() + NUMERICAL_EPS) {
    4540              :             // avoid warning due to numerical instability when stopping at the end of the route
    4541           59 :             myState.myPos = myLane->getLength();
    4542              :         }
    4543              : 
    4544              :     }
    4545    676051550 : }
    4546              : 
    4547              : 
    4548              : 
    4549              : bool
    4550    680112409 : MSVehicle::executeMove() {
    4551              : #ifdef DEBUG_EXEC_MOVE
    4552              :     if (DEBUG_COND) {
    4553              :         std::cout << "\nEXECUTE_MOVE\n"
    4554              :                   << SIMTIME
    4555              :                   << " veh=" << getID()
    4556              :                   << " speed=" << getSpeed() // toString(getSpeed(), 24)
    4557              :                   << std::endl;
    4558              :     }
    4559              : #endif
    4560              : 
    4561              : 
    4562              :     // Maximum safe velocity
    4563    680112409 :     double vSafe = std::numeric_limits<double>::max();
    4564              :     // Minimum safe velocity (lower bound).
    4565    680112409 :     double vSafeMin = -std::numeric_limits<double>::max();
    4566              :     // The distance to a link, which should either be crossed this step
    4567              :     // or in front of which we need to stop.
    4568    680112409 :     double vSafeMinDist = 0;
    4569              : 
    4570    680112409 :     if (myActionStep) {
    4571              :         // Actuate control (i.e. choose bounds for safe speed in current simstep (euler), resp. after current sim step (ballistic))
    4572    608595485 :         processLinkApproaches(vSafe, vSafeMin, vSafeMinDist);
    4573              : #ifdef DEBUG_ACTIONSTEPS
    4574              :         if (DEBUG_COND) {
    4575              :             std::cout << SIMTIME << " vehicle '" << getID() << "'\n"
    4576              :                       "   vsafe from processLinkApproaches(): vsafe " << vSafe << std::endl;
    4577              :         }
    4578              : #endif
    4579              :     } else {
    4580              :         // Continue with current acceleration
    4581     71516924 :         vSafe = getSpeed() + ACCEL2SPEED(myAcceleration);
    4582              : #ifdef DEBUG_ACTIONSTEPS
    4583              :         if (DEBUG_COND) {
    4584              :             std::cout << SIMTIME << " vehicle '" << getID() << "' skips processLinkApproaches()\n"
    4585              :                       "   continues with constant accel " <<  myAcceleration << "...\n"
    4586              :                       << "speed: "  << getSpeed() << " -> " << vSafe << std::endl;
    4587              :         }
    4588              : #endif
    4589              :     }
    4590              : 
    4591              : 
    4592              : //#ifdef DEBUG_EXEC_MOVE
    4593              : //    if (DEBUG_COND) {
    4594              : //        std::cout << "vSafe = " << toString(vSafe,12) << "\n" << std::endl;
    4595              : //    }
    4596              : //#endif
    4597              : 
    4598              :     // Determine vNext = speed after current sim step (ballistic), resp. in current simstep (euler)
    4599              :     // Call to finalizeSpeed applies speed reduction due to dawdling / lane changing but ensures minimum safe speed
    4600    680112409 :     double vNext = vSafe;
    4601    680112409 :     const double rawAccel = SPEED2ACCEL(MAX2(vNext, 0.) - myState.mySpeed);
    4602    680112409 :     if (vNext <= SUMO_const_haltingSpeed * TS && myWaitingTime > MSGlobals::gStartupWaitThreshold && rawAccel <= accelThresholdForWaiting() && myActionStep) {
    4603     68167180 :         myTimeSinceStartup = 0;
    4604    611945229 :     } else if (isStopped()) {
    4605              :         // do not apply startupDelay for waypoints
    4606     17894677 :         if (getCarFollowModel().startupDelayStopped() && getNextStop().pars.speed <= 0) {
    4607        13772 :             myTimeSinceStartup = DELTA_T;
    4608              :         } else {
    4609              :             // do not apply startupDelay but signal that a stop has taken place
    4610     17880905 :             myTimeSinceStartup = getCarFollowModel().getStartupDelay() + DELTA_T;
    4611              :         }
    4612              :     } else {
    4613              :         // identify potential startup (before other effects reduce the speed again)
    4614    594050552 :         myTimeSinceStartup += DELTA_T;
    4615              :     }
    4616    680112409 :     if (myActionStep) {
    4617    608595485 :         vNext = getCarFollowModel().finalizeSpeed(this, vSafe);
    4618    604320560 :         if (vNext > 0) {
    4619    563184344 :             vNext = MAX2(vNext, vSafeMin);
    4620              :         }
    4621              :     }
    4622              :     // (Leo) to avoid tiny oscillations (< 1e-10) of vNext in a standing vehicle column (observed for ballistic update), we cap off vNext
    4623              :     //       (We assure to do this only for vNext<<NUMERICAL_EPS since otherwise this would nullify the workaround for #2995
    4624              :     // (Jakob) We also need to make sure to reach a stop at the start of the next edge
    4625    675837484 :     if (fabs(vNext) < NUMERICAL_EPS_SPEED && (myStopDist > POSITION_EPS || (hasStops() && myCurrEdge == getNextStop().edge))) {
    4626              :         vNext = 0.;
    4627              :     }
    4628              : #ifdef DEBUG_EXEC_MOVE
    4629              :     if (DEBUG_COND) {
    4630              :         std::cout << SIMTIME << " finalizeSpeed vSafe=" << vSafe << " vSafeMin=" << (vSafeMin == -std::numeric_limits<double>::max() ? "-Inf" : toString(vSafeMin))
    4631              :                   << " vNext=" << vNext << " (i.e. accel=" << SPEED2ACCEL(vNext - getSpeed()) << ")" << std::endl;
    4632              :     }
    4633              : #endif
    4634              : 
    4635              :     // vNext may be higher than vSafe without implying a bug:
    4636              :     //  - when approaching a green light that suddenly switches to yellow
    4637              :     //  - when using unregulated junctions
    4638              :     //  - when using tau < step-size
    4639              :     //  - when using unsafe car following models
    4640              :     //  - when using TraCI and some speedMode / laneChangeMode settings
    4641              :     //if (vNext > vSafe + NUMERICAL_EPS) {
    4642              :     //    WRITE_WARNING("vehicle '" + getID() + "' cannot brake hard enough to reach safe speed "
    4643              :     //            + toString(vSafe, 4) + ", moving at " + toString(vNext, 4) + " instead. time="
    4644              :     //            + time2string(MSNet::getInstance()->getCurrentTimeStep()) + ".");
    4645              :     //}
    4646              : 
    4647    675837484 :     if (MSGlobals::gSemiImplicitEulerUpdate) {
    4648              :         vNext = MAX2(vNext, 0.);
    4649              :     } else {
    4650              :         // (Leo) Ballistic: negative vNext can be used to indicate a stop within next step.
    4651              :     }
    4652              : 
    4653              :     // Check for speed advices from the traci client
    4654    675837484 :     vNext = processTraCISpeedControl(vSafe, vNext);
    4655              : 
    4656              :     // the acceleration of a vehicle equipped with the elecHybrid device is restricted by the maximal power of the electric drive as well
    4657    675837484 :     MSDevice_ElecHybrid* elecHybridOfVehicle = dynamic_cast<MSDevice_ElecHybrid*>(getDevice(typeid(MSDevice_ElecHybrid)));
    4658         1135 :     if (elecHybridOfVehicle != nullptr) {
    4659              :         // this is the consumption given by the car following model-computed acceleration
    4660         1135 :         elecHybridOfVehicle->setConsum(elecHybridOfVehicle->consumption(*this, (vNext - this->getSpeed()) / TS, vNext));
    4661              :         // but the maximum power of the electric motor may be lower
    4662              :         // it needs to be converted from [W] to [Wh/s] (3600s / 1h) so that TS can be taken into account
    4663         1135 :         double maxPower = getEmissionParameters()->getDoubleOptional(SUMO_ATTR_MAXIMUMPOWER, 100000.) / 3600;
    4664         1135 :         if (elecHybridOfVehicle->getConsum() / TS > maxPower) {
    4665              :             // no, we cannot accelerate that fast, recompute the maximum possible acceleration
    4666           70 :             double accel = elecHybridOfVehicle->acceleration(*this, maxPower, this->getSpeed());
    4667              :             // and update the speed of the vehicle
    4668           70 :             vNext = MIN2(vNext, this->getSpeed() + accel * TS);
    4669              :             vNext = MAX2(vNext, 0.);
    4670              :             // and set the vehicle consumption to reflect this
    4671           70 :             elecHybridOfVehicle->setConsum(elecHybridOfVehicle->consumption(*this, (vNext - this->getSpeed()) / TS, vNext));
    4672              :         }
    4673              :     }
    4674              : 
    4675    675837484 :     setBrakingSignals(vNext);
    4676              : 
    4677              :     // update position and speed
    4678    675837484 :     int oldLaneOffset = myLane->getEdge().getNumLanes() - myLane->getIndex();
    4679              :     const MSLane* oldLaneMaybeOpposite = myLane;
    4680    675837484 :     if (myLaneChangeModel->isOpposite()) {
    4681              :         // transform to the forward-direction lane, move and then transform back
    4682       409832 :         myState.myPos = myLane->getOppositePos(myState.myPos);
    4683       409832 :         myLane = myLane->getParallelOpposite();
    4684              :     }
    4685    675837484 :     updateState(vNext);
    4686    675837484 :     updateWaitingTime(vNext);
    4687              : 
    4688              :     // Lanes, which the vehicle touched at some moment of the executed simstep
    4689              :     std::vector<MSLane*> passedLanes;
    4690              :     // remember previous lane (myLane is updated in processLaneAdvances)
    4691    675837484 :     const MSLane* oldLane = myLane;
    4692              :     // Reason for a possible emergency stop
    4693              :     std::string emergencyReason;
    4694    675837484 :     processLaneAdvances(passedLanes, emergencyReason);
    4695              : 
    4696    675837484 :     updateTimeLoss(vNext);
    4697    675837484 :     myCollisionImmunity = MAX2((SUMOTime) - 1, myCollisionImmunity - DELTA_T);
    4698              : 
    4699    675837484 :     if (!hasArrivedInternal() && !myLane->getEdge().isVaporizing()) {
    4700    672930356 :         if (myState.myPos > myLane->getLength()) {
    4701          359 :             if (emergencyReason == "") {
    4702           51 :                 emergencyReason = TL(" for unknown reasons");
    4703              :             }
    4704         1436 :             WRITE_WARNINGF(TL("Vehicle '%' performs emergency stop at the end of lane '%'% (decel=%, offset=%), time=%."),
    4705              :                            getID(), myLane->getID(), emergencyReason, myAcceleration - myState.mySpeed,
    4706              :                            myState.myPos - myLane->getLength(), time2string(SIMSTEP));
    4707          359 :             MSNet::getInstance()->getVehicleControl().registerEmergencyStop();
    4708          359 :             MSNet::getInstance()->informVehicleStateListener(this, MSNet::VehicleState::EMERGENCYSTOP);
    4709          359 :             myState.myPos = myLane->getLength();
    4710          359 :             myState.mySpeed = 0;
    4711          359 :             myAcceleration = 0;
    4712              :         }
    4713    672930356 :         const MSLane* oldBackLane = getBackLane();
    4714    672930356 :         if (myLaneChangeModel->isOpposite()) {
    4715              :             passedLanes.clear(); // ignore back occupation
    4716              :         }
    4717              : #ifdef DEBUG_ACTIONSTEPS
    4718              :         if (DEBUG_COND) {
    4719              :             std::cout << SIMTIME << " veh '" << getID() << "' updates further lanes." << std::endl;
    4720              :         }
    4721              : #endif
    4722    672930356 :         myState.myBackPos = updateFurtherLanes(myFurtherLanes, myFurtherLanesPosLat, passedLanes);
    4723    672930356 :         if (passedLanes.size() > 1 && isRail()) {
    4724       731644 :             for (auto pi = passedLanes.rbegin(); pi != passedLanes.rend(); ++pi) {
    4725       554815 :                 MSLane* pLane = *pi;
    4726       554815 :                 if (pLane != myLane && std::find(myFurtherLanes.begin(), myFurtherLanes.end(), pLane) == myFurtherLanes.end()) {
    4727        39518 :                     leaveLaneBack(MSMoveReminder::NOTIFICATION_JUNCTION, *pi);
    4728              :                 }
    4729              :             }
    4730              :         }
    4731              :         // bestLanes need to be updated before lane changing starts. NOTE: This call is also a presumption for updateDriveItems()
    4732    672930356 :         updateBestLanes();
    4733    672930356 :         if (myLane != oldLane || oldBackLane != getBackLane()) {
    4734     21933210 :             if (myLaneChangeModel->getShadowLane() != nullptr || getLateralOverlap() > POSITION_EPS) {
    4735              :                 // shadow lane must be updated if the front or back lane changed
    4736              :                 // either if we already have a shadowLane or if there is lateral overlap
    4737       400383 :                 myLaneChangeModel->updateShadowLane();
    4738              :             }
    4739     21933210 :             if (MSGlobals::gLateralResolution > 0 && !myLaneChangeModel->isOpposite()) {
    4740              :                 // The vehicles target lane must be also be updated if the front or back lane changed
    4741      4293100 :                 myLaneChangeModel->updateTargetLane();
    4742              :             }
    4743              :         }
    4744    672930356 :         setBlinkerInformation(); // needs updated bestLanes
    4745              :         //change the blue light only for emergency vehicles SUMOVehicleClass
    4746    672930356 :         if (myType->getVehicleClass() == SVC_EMERGENCY) {
    4747        85919 :             setEmergencyBlueLight(MSNet::getInstance()->getCurrentTimeStep());
    4748              :         }
    4749              :         // must be done before angle computation
    4750              :         // State needs to be reset for all vehicles before the next call to MSEdgeControl::changeLanes
    4751    672930356 :         if (myActionStep) {
    4752              :             // check (#2681): Can this be skipped?
    4753    601434653 :             myLaneChangeModel->prepareStep();
    4754              :         } else {
    4755     71495703 :             myLaneChangeModel->resetSpeedLat();
    4756              : #ifdef DEBUG_ACTIONSTEPS
    4757              :             if (DEBUG_COND) {
    4758              :                 std::cout << SIMTIME << " veh '" << getID() << "' skips LCM->prepareStep()." << std::endl;
    4759              :             }
    4760              : #endif
    4761              :         }
    4762    672930356 :         myLaneChangeModel->setPreviousAngleOffset(myLaneChangeModel->getAngleOffset());
    4763    672930356 :         myAngle = computeAngle();
    4764              :     }
    4765              : 
    4766              : #ifdef DEBUG_EXEC_MOVE
    4767              :     if (DEBUG_COND) {
    4768              :         std::cout << SIMTIME << " executeMove finished veh=" << getID() << " lane=" << myLane->getID() << " myPos=" << getPositionOnLane() << " myPosLat=" << getLateralPositionOnLane() << "\n";
    4769              :         gDebugFlag1 = false; // See MSLink_DEBUG_OPENED
    4770              :     }
    4771              : #endif
    4772    675837484 :     if (myLaneChangeModel->isOpposite()) {
    4773              :         // transform back to the opposite-direction lane
    4774              :         MSLane* newOpposite = nullptr;
    4775       409832 :         const MSEdge* newOppositeEdge = myLane->getEdge().getOppositeEdge();
    4776       409832 :         if (newOppositeEdge != nullptr) {
    4777       409782 :             newOpposite = newOppositeEdge->getLanes()[newOppositeEdge->getNumLanes() - MAX2(1, oldLaneOffset)];
    4778              : #ifdef DEBUG_EXEC_MOVE
    4779              :             if (DEBUG_COND) {
    4780              :                 std::cout << SIMTIME << "   newOppositeEdge=" << newOppositeEdge->getID() << " oldLaneOffset=" << oldLaneOffset << " leftMost=" << newOppositeEdge->getNumLanes() - 1 << " newOpposite=" << Named::getIDSecure(newOpposite) << "\n";
    4781              :             }
    4782              : #endif
    4783              :         }
    4784       409782 :         if (newOpposite == nullptr) {
    4785           50 :             if (!myLaneChangeModel->hasBlueLight()) {
    4786              :                 // unusual overtaking at junctions is ok for emergency vehicles
    4787            0 :                 WRITE_WARNINGF(TL("Unexpected end of opposite lane for vehicle '%' at lane '%', time=%."),
    4788              :                                getID(), myLane->getID(), time2string(SIMSTEP));
    4789              :             }
    4790           50 :             myLaneChangeModel->changedToOpposite();
    4791           50 :             if (myState.myPos < getLength()) {
    4792              :                 // further lanes is always cleared during opposite driving
    4793           50 :                 MSLane* oldOpposite = oldLane->getOpposite();
    4794           50 :                 if (oldOpposite != nullptr) {
    4795           50 :                     myFurtherLanes.push_back(oldOpposite);
    4796           50 :                     myFurtherLanesPosLat.push_back(0);
    4797              :                     // small value since the lane is going in the other direction
    4798           50 :                     myState.myBackPos = getLength() - myState.myPos;
    4799           50 :                     myAngle = computeAngle();
    4800              :                 } else {
    4801              :                     SOFT_ASSERT(false);
    4802              :                 }
    4803              :             }
    4804              :         } else {
    4805       409782 :             myState.myPos = myLane->getOppositePos(myState.myPos);
    4806       409782 :             myLane = newOpposite;
    4807              :             oldLane = oldLaneMaybeOpposite;
    4808              :             //std::cout << SIMTIME << " updated myLane=" << Named::getIDSecure(myLane) << " oldLane=" << oldLane->getID() << "\n";
    4809       409782 :             myCachedPosition = Position::INVALID;
    4810       409782 :             myLaneChangeModel->updateShadowLane();
    4811              :         }
    4812              :     }
    4813    675837484 :     workOnMoveReminders(myState.myPos - myState.myLastCoveredDist, myState.myPos, myState.mySpeed);
    4814              :     // Return whether the vehicle did move to another lane
    4815   1351674968 :     return myLane != oldLane;
    4816    675837484 : }
    4817              : 
    4818              : void
    4819       214066 : MSVehicle::executeFractionalMove(double dist) {
    4820       214066 :     myState.myPos += dist;
    4821       214066 :     myState.myLastCoveredDist = dist;
    4822       214066 :     myCachedPosition = Position::INVALID;
    4823              : 
    4824       214066 :     const std::vector<const MSLane*> lanes = getUpcomingLanesUntil(dist);
    4825       214066 :     const SUMOTime t = MSNet::getInstance()->getCurrentTimeStep();
    4826       444137 :     for (int i = 0; i < (int)lanes.size(); i++) {
    4827       230071 :         MSLink* link = nullptr;
    4828       230071 :         if (i + 1 < (int)lanes.size()) {
    4829        16005 :             const MSLane* const to = lanes[i + 1];
    4830        16005 :             const bool internal = to->isInternal();
    4831        16010 :             for (MSLink* const l : lanes[i]->getLinkCont()) {
    4832        16010 :                 if ((internal && l->getViaLane() == to) || (!internal && l->getLane() == to)) {
    4833        16005 :                     link = l;
    4834        16005 :                     break;
    4835              :                 }
    4836              :             }
    4837              :         }
    4838       230071 :         myLFLinkLanes.emplace_back(link, getSpeed(), getSpeed(), true, t, getSpeed(), 0, 0, dist);
    4839              :     }
    4840              :     // minimum execute move:
    4841              :     std::vector<MSLane*> passedLanes;
    4842              :     // Reason for a possible emergency stop
    4843       214066 :     if (lanes.size() > 1) {
    4844         4005 :         myLane->removeVehicle(this, MSMoveReminder::NOTIFICATION_JUNCTION, false);
    4845              :     }
    4846              :     std::string emergencyReason;
    4847       214066 :     processLaneAdvances(passedLanes, emergencyReason);
    4848              : #ifdef DEBUG_EXTRAPOLATE_DEPARTPOS
    4849              :     if (DEBUG_COND) {
    4850              :         std::cout << SIMTIME << " veh=" << getID() << " executeFractionalMove dist=" << dist
    4851              :                   << " passedLanes=" << toString(passedLanes) << " lanes=" << toString(lanes)
    4852              :                   << " finalPos=" << myState.myPos
    4853              :                   << " speed=" << getSpeed()
    4854              :                   << " myFurtherLanes=" << toString(myFurtherLanes)
    4855              :                   << "\n";
    4856              :     }
    4857              : #endif
    4858       214066 :     workOnMoveReminders(myState.myPos - myState.myLastCoveredDist, myState.myPos, myState.mySpeed);
    4859       214066 :     if (lanes.size() > 1) {
    4860         4010 :         for (std::vector<MSLane*>::iterator i = myFurtherLanes.begin(); i != myFurtherLanes.end(); ++i) {
    4861              : #ifdef DEBUG_FURTHER
    4862              :             if (DEBUG_COND) {
    4863              :                 std::cout << SIMTIME << " leaveLane \n";
    4864              :             }
    4865              : #endif
    4866            5 :             (*i)->resetPartialOccupation(this);
    4867              :         }
    4868              :         myFurtherLanes.clear();
    4869              :         myFurtherLanesPosLat.clear();
    4870         4005 :         myLane->forceVehicleInsertion(this, getPositionOnLane(), MSMoveReminder::NOTIFICATION_JUNCTION, getLateralPositionOnLane());
    4871              :     }
    4872       214066 : }
    4873              : 
    4874              : 
    4875              : void
    4876    684234477 : MSVehicle::updateState(double vNext, bool parking) {
    4877              :     // update position and speed
    4878              :     double deltaPos; // positional change
    4879    684234477 :     if (MSGlobals::gSemiImplicitEulerUpdate) {
    4880              :         // euler
    4881    584654503 :         deltaPos = SPEED2DIST(vNext);
    4882              :     } else {
    4883              :         // ballistic
    4884     99579974 :         deltaPos = getDeltaPos(SPEED2ACCEL(vNext - myState.mySpeed));
    4885              :     }
    4886              : 
    4887              :     // the *mean* acceleration during the next step (probably most appropriate for emission calculation)
    4888              :     // NOTE: for the ballistic update vNext may be negative, indicating a stop.
    4889    684234477 :     myAcceleration = SPEED2ACCEL(MAX2(vNext, 0.) - myState.mySpeed);
    4890              : 
    4891              : #ifdef DEBUG_EXEC_MOVE
    4892              :     if (DEBUG_COND) {
    4893              :         std::cout << SIMTIME << " updateState() for veh '" << getID() << "': deltaPos=" << deltaPos
    4894              :                   << " pos=" << myState.myPos << " newPos=" << myState.myPos + deltaPos << std::endl;
    4895              :     }
    4896              : #endif
    4897    684234477 :     double decelPlus = -myAcceleration - getCarFollowModel().getMaxDecel() - NUMERICAL_EPS;
    4898    684234477 :     if (decelPlus > 0) {
    4899       420380 :         const double previousAcceleration = SPEED2ACCEL(myState.mySpeed - myState.myPreviousSpeed);
    4900       420380 :         if (myAcceleration + NUMERICAL_EPS < previousAcceleration) {
    4901              :             // vehicle brakes beyond wished maximum deceleration (only warn at the start of the braking manoeuvre)
    4902       289238 :             decelPlus += 2 * NUMERICAL_EPS;
    4903       289238 :             const double emergencyFraction = decelPlus / MAX2(NUMERICAL_EPS, getCarFollowModel().getEmergencyDecel() - getCarFollowModel().getMaxDecel());
    4904       289238 :             if (emergencyFraction >= MSGlobals::gEmergencyDecelWarningThreshold) {
    4905        93756 :                 WRITE_WARNINGF(TL("Vehicle '%' performs emergency braking on lane '%' with decel=%, wished=%, severity=%, time=%."),
    4906              :                                //+ " decelPlus=" + toString(decelPlus)
    4907              :                                //+ " prevAccel=" + toString(previousAcceleration)
    4908              :                                //+ " reserve=" + toString(MAX2(NUMERICAL_EPS, getCarFollowModel().getEmergencyDecel() - getCarFollowModel().getMaxDecel()))
    4909              :                                getID(), myLane->getID(), -myAcceleration, getCarFollowModel().getMaxDecel(), emergencyFraction, time2string(SIMSTEP));
    4910        31252 :                 MSNet::getInstance()->getVehicleControl().registerEmergencyBraking();
    4911              :             }
    4912              :         }
    4913              :     }
    4914              : 
    4915    684234477 :     myState.myPreviousSpeed = myState.mySpeed;
    4916    684234477 :     myState.mySpeed = MAX2(vNext, 0.);
    4917              : 
    4918    684234477 :     if (isRemoteControlled()) {
    4919         7580 :         deltaPos = myInfluencer->implicitDeltaPosRemote(this);
    4920              :     }
    4921              : 
    4922    684234477 :     myState.myPos += deltaPos;
    4923    684234477 :     myState.myLastCoveredDist = deltaPos;
    4924    684234477 :     myNextTurn.first -= deltaPos;
    4925              : 
    4926    684234477 :     if (!parking) {
    4927    675837484 :         myCachedPosition = Position::INVALID;
    4928              :     }
    4929    684234477 : }
    4930              : 
    4931              : void
    4932      8396993 : MSVehicle::updateParkingState() {
    4933      8396993 :     updateState(0, true);
    4934              :     // deboard while parked
    4935      8396993 :     if (myPersonDevice != nullptr) {
    4936       586422 :         myPersonDevice->notifyMove(*this, getPositionOnLane(), getPositionOnLane(), 0);
    4937              :     }
    4938      8396993 :     if (myContainerDevice != nullptr) {
    4939        59887 :         myContainerDevice->notifyMove(*this, getPositionOnLane(), getPositionOnLane(), 0);
    4940              :     }
    4941     16446686 :     for (MSVehicleDevice* const dev : myDevices) {
    4942      8049693 :         dev->notifyParking();
    4943              :     }
    4944      8396993 : }
    4945              : 
    4946              : 
    4947              : void
    4948        30668 : MSVehicle::replaceVehicleType(const MSVehicleType* type) {
    4949        30668 :     MSBaseVehicle::replaceVehicleType(type);
    4950        30668 :     delete myCFVariables;
    4951        30668 :     myCFVariables = type->getCarFollowModel().createVehicleVariables();
    4952        30668 : }
    4953              : 
    4954              : 
    4955              : const MSLane*
    4956   1331519495 : MSVehicle::getBackLane() const {
    4957   1331519495 :     if (myFurtherLanes.size() > 0) {
    4958     17966778 :         return myFurtherLanes.back();
    4959              :     } else {
    4960   1313552717 :         return myLane;
    4961              :     }
    4962              : }
    4963              : 
    4964              : 
    4965              : double
    4966    678310207 : MSVehicle::updateFurtherLanes(std::vector<MSLane*>& furtherLanes, std::vector<double>& furtherLanesPosLat,
    4967              :                               const std::vector<MSLane*>& passedLanes) {
    4968              : #ifdef DEBUG_SETFURTHER
    4969              :     if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID()
    4970              :                                   << " updateFurtherLanes oldFurther=" << toString(furtherLanes)
    4971              :                                   << " oldFurtherPosLat=" << toString(furtherLanesPosLat)
    4972              :                                   << " passed=" << toString(passedLanes)
    4973              :                                   << "\n";
    4974              : #endif
    4975    693856934 :     for (MSLane* further : furtherLanes) {
    4976     15546727 :         further->resetPartialOccupation(this);
    4977     15546727 :         if (further->getBidiLane() != nullptr
    4978     15546727 :                 && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    4979        25789 :             further->getBidiLane()->resetPartialOccupation(this);
    4980              :         }
    4981              :     }
    4982              : 
    4983              :     std::vector<MSLane*> newFurther;
    4984              :     std::vector<double> newFurtherPosLat;
    4985    678310207 :     double backPosOnPreviousLane = myState.myPos - getLength();
    4986              :     bool widthShift = myFurtherLanesPosLat.size() > myFurtherLanes.size();
    4987    678310207 :     if (passedLanes.size() > 1) {
    4988              :         // There are candidates for further lanes. (passedLanes[-1] is the current lane, or current shadow lane in context of updateShadowLanes())
    4989              :         std::vector<MSLane*>::const_iterator fi = furtherLanes.begin();
    4990              :         std::vector<double>::const_iterator fpi = furtherLanesPosLat.begin();
    4991     41746213 :         for (auto pi = passedLanes.rbegin() + 1; pi != passedLanes.rend() && backPosOnPreviousLane < 0; ++pi) {
    4992              :             // As long as vehicle back reaches into passed lane, add it to the further lanes
    4993     15480532 :             MSLane* further = *pi;
    4994     15480532 :             newFurther.push_back(further);
    4995     15480532 :             backPosOnPreviousLane += further->setPartialOccupation(this);
    4996     15480532 :             if (further->getBidiLane() != nullptr
    4997     15480532 :                     && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    4998        25277 :                 further->getBidiLane()->setPartialOccupation(this);
    4999              :             }
    5000     15480532 :             if (fi != furtherLanes.end() && further == *fi) {
    5001              :                 // Lateral position on this lane is already known. Assume constant and use old value.
    5002      6654186 :                 newFurtherPosLat.push_back(*fpi);
    5003              :                 ++fi;
    5004              :                 ++fpi;
    5005              :             } else {
    5006              :                 // The lane *pi was not in furtherLanes before.
    5007              :                 // If it is downstream, we assume as lateral position the current position
    5008              :                 // If it is a new lane upstream (can appear as shadow further in case of LC-maneuvering, e.g.)
    5009              :                 // we assign the last known lateral position.
    5010      8826346 :                 if (newFurtherPosLat.size() == 0) {
    5011      8226148 :                     if (widthShift) {
    5012      1447032 :                         newFurtherPosLat.push_back(myFurtherLanesPosLat.back());
    5013              :                     } else {
    5014      6779116 :                         newFurtherPosLat.push_back(myState.myPosLat);
    5015              :                     }
    5016              :                 } else {
    5017       600198 :                     newFurtherPosLat.push_back(newFurtherPosLat.back());
    5018              :                 }
    5019              :             }
    5020              : #ifdef DEBUG_SETFURTHER
    5021              :             if (DEBUG_COND) {
    5022              :                 std::cout << SIMTIME << " updateFurtherLanes \n"
    5023              :                           << "    further lane '" << further->getID() << "' backPosOnPreviousLane=" << backPosOnPreviousLane
    5024              :                           << std::endl;
    5025              :             }
    5026              : #endif
    5027              :         }
    5028     26265681 :         furtherLanes = newFurther;
    5029     26265681 :         furtherLanesPosLat = newFurtherPosLat;
    5030              :     } else {
    5031              :         furtherLanes.clear();
    5032              :         furtherLanesPosLat.clear();
    5033              :     }
    5034              : #ifdef DEBUG_SETFURTHER
    5035              :     if (DEBUG_COND) std::cout
    5036              :                 << " newFurther=" << toString(furtherLanes)
    5037              :                 << " newFurtherPosLat=" << toString(furtherLanesPosLat)
    5038              :                 << " newBackPos=" << backPosOnPreviousLane
    5039              :                 << "\n";
    5040              : #endif
    5041    678310207 :     return backPosOnPreviousLane;
    5042    678310207 : }
    5043              : 
    5044              : 
    5045              : double
    5046  34165613047 : MSVehicle::getBackPositionOnLane(const MSLane* lane, bool calledByGetPosition) const {
    5047              : #ifdef DEBUG_FURTHER
    5048              :     if (DEBUG_COND) {
    5049              :         std::cout << SIMTIME
    5050              :                   << " getBackPositionOnLane veh=" << getID()
    5051              :                   << " lane=" << Named::getIDSecure(lane)
    5052              :                   << " cbgP=" << calledByGetPosition
    5053              :                   << " pos=" << myState.myPos
    5054              :                   << " backPos=" << myState.myBackPos
    5055              :                   << " myLane=" << myLane->getID()
    5056              :                   << " myLaneBidi=" << Named::getIDSecure(myLane->getBidiLane())
    5057              :                   << " further=" << toString(myFurtherLanes)
    5058              :                   << " furtherPosLat=" << toString(myFurtherLanesPosLat)
    5059              :                   << "\n     shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane())
    5060              :                   << " shadowFurther=" << toString(myLaneChangeModel->getShadowFurtherLanes())
    5061              :                   << " shadowFurtherPosLat=" << toString(myLaneChangeModel->getShadowFurtherLanesPosLat())
    5062              :                   << "\n     targetLane=" << Named::getIDSecure(myLaneChangeModel->getTargetLane())
    5063              :                   << " furtherTargets=" << toString(myLaneChangeModel->getFurtherTargetLanes())
    5064              :                   << std::endl;
    5065              :     }
    5066              : #endif
    5067  34165613047 :     if (lane == myLane
    5068   8086790519 :             || lane == myLaneChangeModel->getShadowLane()
    5069  38767963523 :             || lane == myLaneChangeModel->getTargetLane()) {
    5070  29564837182 :         if (myLaneChangeModel->isOpposite()) {
    5071    231910764 :             if (lane == myLaneChangeModel->getShadowLane()) {
    5072    199120733 :                 return lane->getLength() - myState.myPos - myType->getLength();
    5073              :             } else {
    5074     37737184 :                 return myState.myPos + (calledByGetPosition ? -1 : 1) * myType->getLength();
    5075              :             }
    5076  29332926418 :         } else if (&lane->getEdge() != &myLane->getEdge()) {
    5077     20812223 :             return lane->getLength() - myState.myPos + (calledByGetPosition ? -1 : 1) * myType->getLength();
    5078              :         } else {
    5079              :             // account for parallel lanes of different lengths in the most conservative manner (i.e. while turning)
    5080  58624955134 :             return myState.myPos - myType->getLength() + MIN2(0.0, lane->getLength() - myLane->getLength());
    5081              :         }
    5082   4600775865 :     } else if (lane == myLane->getBidiLane()) {
    5083      3848173 :         return lane->getLength() - myState.myPos + myType->getLength() * (calledByGetPosition ? -1 : 1);
    5084   4598335946 :     } else if (myFurtherLanes.size() > 0 && lane == myFurtherLanes.back()) {
    5085   4544821854 :         return myState.myBackPos;
    5086     53514092 :     } else if ((myLaneChangeModel->getShadowFurtherLanes().size() > 0 && lane == myLaneChangeModel->getShadowFurtherLanes().back())
    5087     54151385 :                || (myLaneChangeModel->getFurtherTargetLanes().size() > 0 && lane == myLaneChangeModel->getFurtherTargetLanes().back())) {
    5088              :         assert(myFurtherLanes.size() > 0);
    5089     20255062 :         if (lane->getLength() == myFurtherLanes.back()->getLength()) {
    5090     19597482 :             return myState.myBackPos;
    5091              :         } else {
    5092              :             // interpolate
    5093              :             //if (DEBUG_COND) {
    5094              :             //if (myFurtherLanes.back()->getLength() != lane->getLength()) {
    5095              :             //    std::cout << SIMTIME << " veh=" << getID() << " lane=" << lane->getID() << " further=" << myFurtherLanes.back()->getID()
    5096              :             //        << " len=" << lane->getLength() << " fLen=" << myFurtherLanes.back()->getLength()
    5097              :             //        << " backPos=" << myState.myBackPos << " result=" << myState.myBackPos / myFurtherLanes.back()->getLength() * lane->getLength() << "\n";
    5098              :             //}
    5099       657580 :             return myState.myBackPos / myFurtherLanes.back()->getLength() * lane->getLength();
    5100              :         }
    5101              :     } else {
    5102              :         //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myFurtherLanes=" << toString(myFurtherLanes) << "\n";
    5103     33259030 :         double leftLength = myType->getLength() - myState.myPos;
    5104              : 
    5105              :         std::vector<MSLane*>::const_iterator i = myFurtherLanes.begin();
    5106     35222452 :         while (leftLength > 0 && i != myFurtherLanes.end()) {
    5107     35194893 :             leftLength -= (*i)->getLength();
    5108              :             //if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
    5109     35194893 :             if (*i == lane) {
    5110     32923238 :                 return -leftLength;
    5111      2271655 :             } else if (*i == lane->getBidiLane()) {
    5112       308233 :                 return lane->getLength() + leftLength - (calledByGetPosition ? 2 * myType->getLength() : 0);
    5113              :             }
    5114              :             ++i;
    5115              :         }
    5116              :         //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myShadowFurtherLanes=" << toString(myLaneChangeModel->getShadowFurtherLanes()) << "\n";
    5117        27559 :         leftLength = myType->getLength() - myState.myPos;
    5118        27559 :         i = myLaneChangeModel->getShadowFurtherLanes().begin();
    5119        27559 :         while (leftLength > 0 && i != myLaneChangeModel->getShadowFurtherLanes().end()) {
    5120        27554 :             leftLength -= (*i)->getLength();
    5121              :             //if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
    5122        27554 :             if (*i == lane) {
    5123        27554 :                 return -leftLength;
    5124              :             }
    5125              :             ++i;
    5126              :         }
    5127              :         //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myFurtherTargetLanes=" << toString(myLaneChangeModel->getFurtherTargetLanes()) << "\n";
    5128              :         leftLength = myType->getLength() - myState.myPos;
    5129              :         i = getFurtherLanes().begin();
    5130            5 :         const std::vector<MSLane*> furtherTargetLanes = myLaneChangeModel->getFurtherTargetLanes();
    5131              :         auto j = furtherTargetLanes.begin();
    5132            5 :         while (leftLength > 0 && j != furtherTargetLanes.end()) {
    5133            2 :             leftLength -= (*i)->getLength();
    5134              :             // if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
    5135            2 :             if (*j == lane) {
    5136            2 :                 return -leftLength;
    5137              :             }
    5138              :             ++i;
    5139              :             ++j;
    5140              :         }
    5141           21 :         WRITE_WARNING("Request backPos of vehicle '" + getID() + "' for invalid lane '" + Named::getIDSecure(lane)
    5142              :                       + "' time=" + time2string(MSNet::getInstance()->getCurrentTimeStep()) + ".")
    5143              :         SOFT_ASSERT(false);
    5144            3 :         return  myState.myBackPos;
    5145            5 :     }
    5146              : }
    5147              : 
    5148              : 
    5149              : double
    5150  28013783101 : MSVehicle::getPositionOnLane(const MSLane* lane) const {
    5151  28013783101 :     return getBackPositionOnLane(lane, true) + myType->getLength();
    5152              : }
    5153              : 
    5154              : 
    5155              : bool
    5156    421163487 : MSVehicle::isFrontOnLane(const MSLane* lane) const {
    5157    421163487 :     return lane == myLane || lane == myLaneChangeModel->getShadowLane() || lane == myLane->getBidiLane();
    5158              : }
    5159              : 
    5160              : 
    5161              : void
    5162    608595485 : MSVehicle::checkRewindLinkLanes(const double lengthsInFront, DriveItemVector& lfLinks) const {
    5163    608595485 :     if (MSGlobals::gUsingInternalLanes && !myLane->getEdge().isRoundabout() && !myLaneChangeModel->isOpposite()) {
    5164    605393422 :         double seenSpace = -lengthsInFront;
    5165              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5166              :         if (DEBUG_COND) {
    5167              :             std::cout << "\nCHECK_REWIND_LINKLANES\n" << " veh=" << getID() << " lengthsInFront=" << lengthsInFront << "\n";
    5168              :         };
    5169              : #endif
    5170    605393422 :         bool foundStopped = false;
    5171              :         // compute available space until a stopped vehicle is found
    5172              :         // this is the sum of non-interal lane length minus in-between vehicle lengths
    5173   1749479093 :         for (int i = 0; i < (int)lfLinks.size(); ++i) {
    5174              :             // skip unset links
    5175   1144085671 :             DriveProcessItem& item = lfLinks[i];
    5176              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5177              :             if (DEBUG_COND) std::cout << SIMTIME
    5178              :                                           << " link=" << (item.myLink == 0 ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
    5179              :                                           << " foundStopped=" << foundStopped;
    5180              : #endif
    5181   1144085671 :             if (item.myLink == nullptr || foundStopped) {
    5182    382779396 :                 if (!foundStopped) {
    5183    335084439 :                     item.availableSpace += seenSpace;
    5184              :                 } else {
    5185     47694957 :                     item.availableSpace = seenSpace;
    5186              :                 }
    5187              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5188              :                 if (DEBUG_COND) {
    5189              :                     std::cout << " avail=" << item.availableSpace << "\n";
    5190              :                 }
    5191              : #endif
    5192    382779396 :                 continue;
    5193              :             }
    5194              :             // get the next lane, determine whether it is an internal lane
    5195              :             const MSLane* approachedLane = item.myLink->getViaLane();
    5196    761306275 :             if (approachedLane != nullptr) {
    5197    411958179 :                 if (keepClear(item.myLink)) {
    5198    124374116 :                     seenSpace = seenSpace - approachedLane->getBruttoVehLenSum();
    5199    124374116 :                     if (approachedLane == myLane) {
    5200        52319 :                         seenSpace += getVehicleType().getLengthWithGap();
    5201              :                     }
    5202              :                 } else {
    5203    287584063 :                     seenSpace = seenSpace + approachedLane->getSpaceTillLastStanding(this, foundStopped);// - approachedLane->getBruttoVehLenSum() + approachedLane->getLength();
    5204              :                 }
    5205    411958179 :                 item.availableSpace = seenSpace;
    5206              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5207              :                 if (DEBUG_COND) std::cout
    5208              :                             << " approached=" << approachedLane->getID()
    5209              :                             << " approachedBrutto=" << approachedLane->getBruttoVehLenSum()
    5210              :                             << " avail=" << item.availableSpace
    5211              :                             << " seenSpace=" << seenSpace
    5212              :                             << " hadStoppedVehicle=" << item.hadStoppedVehicle
    5213              :                             << " lengthsInFront=" << lengthsInFront
    5214              :                             << "\n";
    5215              : #endif
    5216    411958179 :                 continue;
    5217              :             }
    5218              :             approachedLane = item.myLink->getLane();
    5219    349348096 :             const MSVehicle* last = approachedLane->getLastAnyVehicle();
    5220    349348096 :             if (last == nullptr || last == this) {
    5221     54430087 :                 if (approachedLane->getLength() > getVehicleType().getLength()
    5222     54430087 :                         || keepClear(item.myLink)) {
    5223     52204121 :                     seenSpace += approachedLane->getLength();
    5224              :                 }
    5225     54430087 :                 item.availableSpace = seenSpace;
    5226              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5227              :                 if (DEBUG_COND) {
    5228              :                     std::cout << " last=" << Named::getIDSecure(last) << " laneLength=" << approachedLane->getLength() << " avail=" << item.availableSpace << "\n";
    5229              :                 }
    5230              : #endif
    5231              :             } else {
    5232    294918009 :                 bool foundStopped2 = false;
    5233    294918009 :                 double spaceTillLastStanding = approachedLane->getSpaceTillLastStanding(this, foundStopped2);
    5234    294918009 :                 if (approachedLane->getBidiLane() != nullptr) {
    5235        79964 :                     const MSVehicle* oncomingVeh = approachedLane->getBidiLane()->getFirstFullVehicle();
    5236        79964 :                     if (oncomingVeh) {
    5237        26576 :                         const double oncomingGap = approachedLane->getLength() - oncomingVeh->getPositionOnLane();
    5238        26576 :                         const double oncomingBGap = oncomingVeh->getBrakeGap(true);
    5239              :                         // oncoming movement until ego enters the junction
    5240        26576 :                         const double oncomingMove = STEPS2TIME(item.myArrivalTime - SIMSTEP) * oncomingVeh->getSpeed();
    5241        26576 :                         const double spaceTillOncoming = oncomingGap - oncomingBGap - oncomingMove;
    5242              :                         spaceTillLastStanding = MIN2(spaceTillLastStanding, spaceTillOncoming);
    5243        26576 :                         if (spaceTillOncoming <= getVehicleType().getLengthWithGap()) {
    5244        21724 :                             foundStopped = true;
    5245              :                         }
    5246              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5247              :                         if (DEBUG_COND) {
    5248              :                             std::cout << " oVeh=" << oncomingVeh->getID()
    5249              :                                       << " oGap=" << oncomingGap
    5250              :                                       << " bGap=" << oncomingBGap
    5251              :                                       << " mGap=" << oncomingMove
    5252              :                                       << " sto=" << spaceTillOncoming;
    5253              :                         }
    5254              : #endif
    5255              :                     }
    5256              :                 }
    5257    294918009 :                 seenSpace += spaceTillLastStanding;
    5258    294918009 :                 if (foundStopped2) {
    5259     19041281 :                     foundStopped = true;
    5260     19041281 :                     item.hadStoppedVehicle = true;
    5261              :                 }
    5262    294918009 :                 item.availableSpace = seenSpace;
    5263    294918009 :                 if (last->myHaveToWaitOnNextLink || last->isStopped()) {
    5264     29333751 :                     foundStopped = true;
    5265     29333751 :                     item.hadStoppedVehicle = true;
    5266              :                 }
    5267              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5268              :                 if (DEBUG_COND) std::cout
    5269              :                             << " approached=" << approachedLane->getID()
    5270              :                             << " last=" << last->getID()
    5271              :                             << " lastHasToWait=" << last->myHaveToWaitOnNextLink
    5272              :                             << " lastBrakeLight=" << last->signalSet(VEH_SIGNAL_BRAKELIGHT)
    5273              :                             << " lastBrakeGap=" << last->getCarFollowModel().brakeGap(last->getSpeed())
    5274              :                             << " lastGap=" << (last->getBackPositionOnLane(approachedLane) + last->getCarFollowModel().brakeGap(last->getSpeed()) - last->getSpeed() * last->getCarFollowModel().getHeadwayTime()
    5275              :                                                // gap of last up to the next intersection
    5276              :                                                - last->getVehicleType().getMinGap())
    5277              :                             << " stls=" << spaceTillLastStanding
    5278              :                             << " avail=" << item.availableSpace
    5279              :                             << " seenSpace=" << seenSpace
    5280              :                             << " foundStopped=" << foundStopped
    5281              :                             << " foundStopped2=" << foundStopped2
    5282              :                             << "\n";
    5283              : #endif
    5284              :             }
    5285              :         }
    5286              : 
    5287              :         // check which links allow continuation and add pass available to the previous item
    5288   1144085671 :         for (int i = ((int)lfLinks.size() - 1); i > 0; --i) {
    5289    538692249 :             DriveProcessItem& item = lfLinks[i - 1];
    5290    538692249 :             DriveProcessItem& nextItem = lfLinks[i];
    5291    538692249 :             const bool canLeaveJunction = item.myLink->getViaLane() == nullptr || nextItem.myLink == nullptr || nextItem.mySetRequest;
    5292              :             const bool opened = (item.myLink != nullptr
    5293    538692249 :                                  && (canLeaveJunction || (
    5294              :                                          // indirect bicycle turn
    5295     25008679 :                                          nextItem.myLink != nullptr && nextItem.myLink->isInternalJunctionLink() && nextItem.myLink->haveRed()))
    5296    513697632 :                                  && (
    5297    513697632 :                                      item.myLink->havePriority()
    5298     25241849 :                                      || i == 1 // the upcoming link (item 0) is checked in executeMove anyway. No need to use outdata approachData here
    5299      4533813 :                                      || (myInfluencer != nullptr && !myInfluencer->getRespectJunctionPriority())
    5300      4504297 :                                      || item.myLink->opened(item.myArrivalTime, item.myArrivalSpeed,
    5301      4504297 :                                              item.getLeaveSpeed(), getVehicleType().getLength(),
    5302      4504297 :                                              getImpatience(), getCarFollowModel().getMaxDecel(), getWaitingTime(), getLateralPositionOnLane(), nullptr, false, this)));
    5303    538692249 :             bool allowsContinuation = (item.myLink == nullptr || item.myLink->isCont() || opened) && !item.hadStoppedVehicle;
    5304              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5305              :             if (DEBUG_COND) std::cout
    5306              :                         << "   link=" << (item.myLink == 0 ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
    5307              :                         << " canLeave=" << canLeaveJunction
    5308              :                         << " opened=" << opened
    5309              :                         << " allowsContinuation=" << allowsContinuation
    5310              :                         << " foundStopped=" << foundStopped
    5311              :                         << "\n";
    5312              : #endif
    5313    538692249 :             if (!opened && item.myLink != nullptr) {
    5314     25572032 :                 foundStopped = true;
    5315     25572032 :                 if (i > 1) {
    5316      4043885 :                     DriveProcessItem& item2 = lfLinks[i - 2];
    5317      4043885 :                     if (item2.myLink != nullptr && item2.myLink->isCont()) {
    5318              :                         allowsContinuation = true;
    5319              :                     }
    5320              :                 }
    5321              :             }
    5322    536272752 :             if (allowsContinuation) {
    5323    483374040 :                 item.availableSpace = nextItem.availableSpace;
    5324              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5325              :                 if (DEBUG_COND) std::cout
    5326              :                             << "   link=" << (item.myLink == nullptr ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
    5327              :                             << " copy nextAvail=" << nextItem.availableSpace
    5328              :                             << "\n";
    5329              : #endif
    5330              :             }
    5331              :         }
    5332              : 
    5333              :         // find removalBegin
    5334              :         int removalBegin = -1;
    5335    723556503 :         for (int i = 0; foundStopped && i < (int)lfLinks.size() && removalBegin < 0; ++i) {
    5336              :             // skip unset links
    5337    118163081 :             const DriveProcessItem& item = lfLinks[i];
    5338    118163081 :             if (item.myLink == nullptr) {
    5339      5573764 :                 continue;
    5340              :             }
    5341              :             /*
    5342              :             double impatienceCorrection = MAX2(0., double(double(myWaitingTime)));
    5343              :             if (seenSpace<getVehicleType().getLengthWithGap()-impatienceCorrection/10.&&nextSeenNonInternal!=0) {
    5344              :                 removalBegin = lastLinkToInternal;
    5345              :             }
    5346              :             */
    5347              : 
    5348    112589317 :             const double leftSpace = item.availableSpace - getVehicleType().getLengthWithGap();
    5349              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5350              :             if (DEBUG_COND) std::cout
    5351              :                         << SIMTIME
    5352              :                         << " veh=" << getID()
    5353              :                         << " link=" << (item.myLink == 0 ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
    5354              :                         << " avail=" << item.availableSpace
    5355              :                         << " leftSpace=" << leftSpace
    5356              :                         << "\n";
    5357              : #endif
    5358    112589317 :             if (leftSpace < 0/* && item.myLink->willHaveBlockedFoe()*/) {
    5359              :                 double impatienceCorrection = 0;
    5360              :                 /*
    5361              :                 if(item.myLink->getState()==LINKSTATE_MINOR) {
    5362              :                     impatienceCorrection = MAX2(0., STEPS2TIME(myWaitingTime));
    5363              :                 }
    5364              :                 */
    5365              :                 // may ignore keepClear rules
    5366     71459660 :                 if (leftSpace < -impatienceCorrection / 10. && keepClear(item.myLink)) {
    5367              :                     removalBegin = i;
    5368              :                 }
    5369              :                 //removalBegin = i;
    5370              :             }
    5371              :         }
    5372              :         // abort requests
    5373    605393422 :         if (removalBegin != -1 && !(removalBegin == 0 && myLane->getEdge().isInternal())) {
    5374     29135475 :             const double brakeGap = getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0.);
    5375     99583917 :             while (removalBegin < (int)(lfLinks.size())) {
    5376     74979389 :                 DriveProcessItem& dpi = lfLinks[removalBegin];
    5377     74979389 :                 if (dpi.myLink == nullptr) {
    5378              :                     break;
    5379              :                 }
    5380     70448442 :                 dpi.myVLinkPass = dpi.myVLinkWait;
    5381              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5382              :                 if (DEBUG_COND) {
    5383              :                     std::cout << " removalBegin=" << removalBegin << " brakeGap=" << brakeGap << " dist=" << dpi.myDistance << " speed=" << myState.mySpeed << " a2s=" << ACCEL2SPEED(getCarFollowModel().getMaxDecel()) << "\n";
    5384              :                 }
    5385              : #endif
    5386     70448442 :                 if (dpi.myDistance >= brakeGap + POSITION_EPS) {
    5387              :                     // always leave junctions after requesting to enter
    5388     70439079 :                     if (!dpi.myLink->isExitLink() || !lfLinks[removalBegin - 1].mySetRequest) {
    5389     70431098 :                         dpi.mySetRequest = false;
    5390              :                     }
    5391              :                 }
    5392     70448442 :                 ++removalBegin;
    5393              :             }
    5394              :         }
    5395              :     }
    5396    608595485 : }
    5397              : 
    5398              : 
    5399              : void
    5400    680112409 : MSVehicle::setApproachingForAllLinks() {
    5401    680112409 :     if (!myActionStep) {
    5402              :         return;
    5403              :     }
    5404    608595485 :     removeApproachingInformation(myLFLinkLanesPrev);
    5405   1760504853 :     for (DriveProcessItem& dpi : myLFLinkLanes) {
    5406   1151909368 :         if (dpi.myLink != nullptr) {
    5407    809514415 :             if (dpi.myLink->getState() == LINKSTATE_ALLWAY_STOP) {
    5408      2722956 :                 dpi.myArrivalTime += (SUMOTime)RandHelper::rand((int)2, getRNG()); // tie braker
    5409              :             }
    5410    809514415 :             dpi.myLink->setApproaching(this, dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
    5411    809514415 :                                        dpi.mySetRequest, dpi.myArrivalSpeedBraking, getWaitingTimeFor(dpi.myLink), dpi.myDistance, getLateralPositionOnLane());
    5412              :         }
    5413              :     }
    5414    608595485 :     if (isRail()) {
    5415      7488977 :         for (DriveProcessItem& dpi : myLFLinkLanes) {
    5416      6266720 :             if (dpi.myLink != nullptr && dpi.myLink->getTLLogic() != nullptr && dpi.myLink->getTLLogic()->getLogicType() == TrafficLightType::RAIL_SIGNAL) {
    5417       550470 :                 MSRailSignalControl::getInstance().notifyApproach(dpi.myLink);
    5418              :             }
    5419              :         }
    5420              :     }
    5421    608595485 :     if (myLaneChangeModel->getShadowLane() != nullptr) {
    5422              :         // register on all shadow links
    5423      7334527 :         for (const DriveProcessItem& dpi : myLFLinkLanes) {
    5424      4852316 :             if (dpi.myLink != nullptr) {
    5425      3328298 :                 MSLink* parallelLink = dpi.myLink->getParallelLink(myLaneChangeModel->getShadowDirection());
    5426      3328298 :                 if (parallelLink == nullptr && getLaneChangeModel().isOpposite() && dpi.myLink->isEntryLink()) {
    5427              :                     // register on opposite direction entry link to warn foes at minor side road
    5428       170031 :                     parallelLink = dpi.myLink->getOppositeDirectionLink();
    5429              :                 }
    5430      3328298 :                 if (parallelLink != nullptr) {
    5431      2365712 :                     const double latOffset = getLane()->getRightSideOnEdge() - myLaneChangeModel->getShadowLane()->getRightSideOnEdge();
    5432      2365712 :                     parallelLink->setApproaching(this, dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
    5433      2365712 :                                                  dpi.mySetRequest, dpi.myArrivalSpeedBraking, getWaitingTimeFor(dpi.myLink), dpi.myDistance,
    5434              :                                                  latOffset);
    5435      2365712 :                     myLaneChangeModel->setShadowApproachingInformation(parallelLink);
    5436              :                 }
    5437              :             }
    5438              :         }
    5439              :     }
    5440              : #ifdef DEBUG_PLAN_MOVE
    5441              :     if (DEBUG_COND) {
    5442              :         std::cout << SIMTIME
    5443              :                   << " veh=" << getID()
    5444              :                   << " after checkRewindLinkLanes\n";
    5445              :         for (DriveProcessItem& dpi : myLFLinkLanes) {
    5446              :             std::cout
    5447              :                     << " vPass=" << dpi.myVLinkPass
    5448              :                     << " vWait=" << dpi.myVLinkWait
    5449              :                     << " linkLane=" << (dpi.myLink == 0 ? "NULL" : dpi.myLink->getViaLaneOrLane()->getID())
    5450              :                     << " request=" << dpi.mySetRequest
    5451              :                     << " atime=" << dpi.myArrivalTime
    5452              :                     << "\n";
    5453              :         }
    5454              :     }
    5455              : #endif
    5456              : }
    5457              : 
    5458              : 
    5459              : void
    5460         1669 : MSVehicle::registerInsertionApproach(MSLink* link, double dist) {
    5461              :     DriveProcessItem dpi(0, dist);
    5462         1669 :     dpi.myLink = link;
    5463         1669 :     const double arrivalSpeedBraking = getCarFollowModel().getMinimalArrivalSpeedEuler(dist, getSpeed());
    5464         1669 :     link->setApproaching(this, SUMOTime_MAX, 0, 0, false, arrivalSpeedBraking, 0, dpi.myDistance, 0);
    5465              :     // ensure cleanup in the next step
    5466         1669 :     myLFLinkLanes.push_back(dpi);
    5467         1669 :     MSRailSignalControl::getInstance().notifyApproach(link);
    5468         1669 : }
    5469              : 
    5470              : 
    5471              : void
    5472     17773882 : MSVehicle::enterLaneAtMove(MSLane* enteredLane, bool onTeleporting) {
    5473     17773882 :     myAmOnNet = !onTeleporting;
    5474              :     // vaporizing edge?
    5475              :     /*
    5476              :     if (enteredLane->getEdge().isVaporizing()) {
    5477              :         // yep, let's do the vaporization...
    5478              :         myLane = enteredLane;
    5479              :         return true;
    5480              :     }
    5481              :     */
    5482              :     // Adjust MoveReminder offset to the next lane
    5483     17773882 :     adaptLaneEntering2MoveReminder(*enteredLane);
    5484              :     // set the entered lane as the current lane
    5485     17773882 :     MSLane* oldLane = myLane;
    5486     17773882 :     myLane = enteredLane;
    5487     17773882 :     myLastBestLanesEdge = nullptr;
    5488              : 
    5489              :     // internal edges are not a part of the route...
    5490     17773882 :     if (!enteredLane->getEdge().isInternal()) {
    5491              :         ++myCurrEdge;
    5492              :         assert(myLaneChangeModel->isOpposite() || haveValidStopEdges());
    5493              :     }
    5494     17773882 :     if (myInfluencer != nullptr) {
    5495         9101 :         myInfluencer->adaptLaneTimeLine(myLane->getIndex() - oldLane->getIndex());
    5496              :     }
    5497     17773882 :     if (!onTeleporting) {
    5498     17756864 :         activateReminders(MSMoveReminder::NOTIFICATION_JUNCTION, enteredLane);
    5499     17756864 :         if (MSGlobals::gLateralResolution > 0) {
    5500      3738231 :             myFurtherLanesPosLat.push_back(myState.myPosLat);
    5501              :             // transform lateral position when the lane width changes
    5502              :             assert(oldLane != nullptr);
    5503      3738231 :             const MSLink* const link = oldLane->getLinkTo(myLane);
    5504      3738231 :             if (link != nullptr) {
    5505      3738189 :                 myState.myPosLat += link->getLateralShift();
    5506              :             } else {
    5507           42 :                 myState.myPosLat += (oldLane->getCenterOnEdge() - myLane->getCanonicalPredecessorLane()->getRightSideOnEdge()) / 2;
    5508              :             }
    5509     14018633 :         } else if (fabs(myState.myPosLat) > NUMERICAL_EPS) {
    5510       195813 :             const double overlap = MAX2(0.0, getLateralOverlap(myState.myPosLat, oldLane));
    5511       195813 :             const double range = (oldLane->getWidth() - getVehicleType().getWidth()) * 0.5 + overlap;
    5512       195813 :             const double range2 = (myLane->getWidth() - getVehicleType().getWidth()) * 0.5 + overlap;
    5513       195813 :             myState.myPosLat *= range2 / range;
    5514              :         }
    5515     17756864 :         if (myLane->getBidiLane() != nullptr && (!isRailway(getVClass()) || (myLane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5516              :             // railways don't need to "see" each other when moving in opposite directions on the same track (efficiency)
    5517              :             // (unless the lane is shared with cars)
    5518         9357 :             myLane->getBidiLane()->setPartialOccupation(this);
    5519              :         }
    5520              :     } else {
    5521              :         // normal move() isn't called so reset position here. must be done
    5522              :         // before calling reminders
    5523        17018 :         myState.myPos = 0;
    5524        17018 :         myCachedPosition = Position::INVALID;
    5525        17018 :         activateReminders(MSMoveReminder::NOTIFICATION_TELEPORT, enteredLane);
    5526              :     }
    5527              :     // update via
    5528     17773882 :     if (myParameter->via.size() > 0 &&  myLane->getEdge().getID() == myParameter->via.front()) {
    5529         5725 :         myParameter->via.erase(myParameter->via.begin());
    5530              :     }
    5531     17773882 : }
    5532              : 
    5533              : 
    5534              : void
    5535      1070401 : MSVehicle::enterLaneAtLaneChange(MSLane* enteredLane) {
    5536      1070401 :     myAmOnNet = true;
    5537      1070401 :     myLane = enteredLane;
    5538      1070401 :     myCachedPosition = Position::INVALID;
    5539              :     // need to update myCurrentLaneInBestLanes
    5540      1070401 :     updateBestLanes();
    5541              :     // switch to and activate the new lane's reminders
    5542              :     // keep OldLaneReminders
    5543      1265200 :     for (std::vector< MSMoveReminder* >::const_iterator rem = enteredLane->getMoveReminders().begin(); rem != enteredLane->getMoveReminders().end(); ++rem) {
    5544       194799 :         addReminder(*rem);
    5545              :     }
    5546      1070401 :     activateReminders(MSMoveReminder::NOTIFICATION_LANE_CHANGE, enteredLane);
    5547      1070401 :     MSLane* lane = myLane;
    5548      1070401 :     double leftLength = getVehicleType().getLength() - myState.myPos;
    5549              :     int deleteFurther = 0;
    5550              : #ifdef DEBUG_SETFURTHER
    5551              :     if (DEBUG_COND) {
    5552              :         std::cout << SIMTIME << " enterLaneAtLaneChange entered=" << Named::getIDSecure(enteredLane) << " oldFurther=" << toString(myFurtherLanes) << "\n";
    5553              :     }
    5554              : #endif
    5555      1070401 :     if (myLane->getBidiLane() != nullptr && (!isRailway(getVClass()) || (myLane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5556              :         // railways don't need to "see" each other when moving in opposite directions on the same track (efficiency)
    5557              :         // (unless the lane is shared with cars)
    5558         8352 :         myLane->getBidiLane()->setPartialOccupation(this);
    5559              :     }
    5560      1152763 :     for (int i = 0; i < (int)myFurtherLanes.size(); i++) {
    5561        82362 :         if (lane != nullptr) {
    5562        79287 :             lane = lane->getLogicalPredecessorLane(myFurtherLanes[i]->getEdge());
    5563              :         }
    5564              : #ifdef DEBUG_SETFURTHER
    5565              :         if (DEBUG_COND) {
    5566              :             std::cout << "  enterLaneAtLaneChange i=" << i << " lane=" << Named::getIDSecure(lane) << " leftLength=" << leftLength << "\n";
    5567              :         }
    5568              : #endif
    5569        82362 :         if (leftLength > 0) {
    5570        81784 :             if (lane != nullptr) {
    5571        32059 :                 myFurtherLanes[i]->resetPartialOccupation(this);
    5572        32059 :                 if (myFurtherLanes[i]->getBidiLane() != nullptr
    5573        32059 :                         && (!isRailway(getVClass()) || (myFurtherLanes[i]->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5574           45 :                     myFurtherLanes[i]->getBidiLane()->resetPartialOccupation(this);
    5575              :                 }
    5576              :                 // lane changing onto longer lanes may reduce the number of
    5577              :                 // remaining further lanes
    5578        32059 :                 myFurtherLanes[i] = lane;
    5579        32059 :                 myFurtherLanesPosLat[i] = myState.myPosLat;
    5580        32059 :                 leftLength -= lane->setPartialOccupation(this);
    5581        32059 :                 if (lane->getBidiLane() != nullptr
    5582        32059 :                         && (!isRailway(getVClass()) || (lane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5583          552 :                     lane->getBidiLane()->setPartialOccupation(this);
    5584              :                 }
    5585        32059 :                 myState.myBackPos = -leftLength;
    5586              : #ifdef DEBUG_SETFURTHER
    5587              :                 if (DEBUG_COND) {
    5588              :                     std::cout << SIMTIME << "   newBackPos=" << myState.myBackPos << "\n";
    5589              :                 }
    5590              : #endif
    5591              :             } else {
    5592              :                 // keep the old values, but ensure there is no shadow
    5593        49725 :                 if (myLaneChangeModel->isChangingLanes()) {
    5594            0 :                     myLaneChangeModel->setNoShadowPartialOccupator(myFurtherLanes[i]);
    5595              :                 }
    5596        49725 :                 if (myState.myBackPos < 0) {
    5597           51 :                     myState.myBackPos += myFurtherLanes[i]->getLength();
    5598              :                 }
    5599              : #ifdef DEBUG_SETFURTHER
    5600              :                 if (DEBUG_COND) {
    5601              :                     std::cout << SIMTIME << "   i=" << i << " further=" << myFurtherLanes[i]->getID() << " newBackPos=" << myState.myBackPos << "\n";
    5602              :                 }
    5603              : #endif
    5604              :             }
    5605              :         } else {
    5606          578 :             myFurtherLanes[i]->resetPartialOccupation(this);
    5607          578 :             if (myFurtherLanes[i]->getBidiLane() != nullptr
    5608          578 :                     && (!isRailway(getVClass()) || (myFurtherLanes[i]->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5609            0 :                 myFurtherLanes[i]->getBidiLane()->resetPartialOccupation(this);
    5610              :             }
    5611          578 :             deleteFurther++;
    5612              :         }
    5613              :     }
    5614      1070401 :     if (deleteFurther > 0) {
    5615              : #ifdef DEBUG_SETFURTHER
    5616              :         if (DEBUG_COND) {
    5617              :             std::cout << SIMTIME << " veh=" << getID() << " shortening myFurtherLanes by " << deleteFurther << "\n";
    5618              :         }
    5619              : #endif
    5620          553 :         myFurtherLanes.erase(myFurtherLanes.end() - deleteFurther, myFurtherLanes.end());
    5621          553 :         myFurtherLanesPosLat.erase(myFurtherLanesPosLat.end() - deleteFurther, myFurtherLanesPosLat.end());
    5622              :     }
    5623              : #ifdef DEBUG_SETFURTHER
    5624              :     if (DEBUG_COND) {
    5625              :         std::cout << SIMTIME << " enterLaneAtLaneChange new furtherLanes=" << toString(myFurtherLanes)
    5626              :                   << " furterLanesPosLat=" << toString(myFurtherLanesPosLat) << "\n";
    5627              :     }
    5628              : #endif
    5629      1070401 :     myAngle = computeAngle();
    5630      1070401 : }
    5631              : 
    5632              : 
    5633              : void
    5634      3121471 : MSVehicle::computeFurtherLanes(MSLane* enteredLane, double pos, bool collision) {
    5635              :     // build the list of lanes the vehicle is lapping into
    5636      3121471 :     if (!myLaneChangeModel->isOpposite()) {
    5637      3099805 :         double leftLength = myType->getLength() - pos;
    5638      3099805 :         MSLane* clane = enteredLane;
    5639      3099805 :         int routeIndex = getRoutePosition();
    5640      3199655 :         while (leftLength > 0) {
    5641       218432 :             if (routeIndex > 0 && clane->getEdge().isNormal()) {
    5642              :                 // get predecessor lane that corresponds to prior route
    5643         4434 :                 routeIndex--;
    5644         4434 :                 const MSEdge* fromRouteEdge = myRoute->getEdges()[routeIndex];
    5645              :                 MSLane* target = clane;
    5646         4434 :                 clane = nullptr;
    5647         5804 :                 for (auto ili : target->getIncomingLanes()) {
    5648         5797 :                     if (ili.lane->getEdge().getNormalBefore() == fromRouteEdge) {
    5649         4427 :                         clane = ili.lane;
    5650         4427 :                         break;
    5651              :                     }
    5652              :                 }
    5653              :             } else {
    5654       213998 :                 clane = clane->getLogicalPredecessorLane();
    5655              :             }
    5656       128988 :             if (clane == nullptr || clane == myLane || clane == myLane->getBidiLane()
    5657       347412 :                     || (clane->isInternal() && (
    5658       105937 :                             clane->getLinkCont()[0]->getDirection() == LinkDirection::TURN
    5659        76807 :                             || clane->getLinkCont()[0]->getDirection() == LinkDirection::TURN_LEFTHAND))) {
    5660              :                 break;
    5661              :             }
    5662        99850 :             if (!collision || std::find(myFurtherLanes.begin(), myFurtherLanes.end(), clane) == myFurtherLanes.end()) {
    5663        99387 :                 myFurtherLanes.push_back(clane);
    5664        99387 :                 myFurtherLanesPosLat.push_back(myState.myPosLat);
    5665        99387 :                 clane->setPartialOccupation(this);
    5666        99387 :                 if (clane->getBidiLane() != nullptr
    5667        99387 :                         && (!isRailway(getVClass()) || (clane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5668            5 :                     clane->getBidiLane()->setPartialOccupation(this);
    5669              :                 }
    5670              :             }
    5671        99850 :             leftLength -= clane->getLength();
    5672              :         }
    5673      3099805 :         myState.myBackPos = -leftLength;
    5674              : #ifdef DEBUG_SETFURTHER
    5675              :         if (DEBUG_COND) {
    5676              :             std::cout << SIMTIME << " computeFurtherLanes veh=" << getID() << " pos=" << pos << " myFurtherLanes=" << toString(myFurtherLanes) << " backPos=" << myState.myBackPos << "\n";
    5677              :         }
    5678              : #endif
    5679              :     } else {
    5680              :         // clear partial occupation
    5681        22074 :         for (MSLane* further : myFurtherLanes) {
    5682              : #ifdef DEBUG_SETFURTHER
    5683              :             if (DEBUG_COND) {
    5684              :                 std::cout << SIMTIME << " opposite: resetPartialOccupation " << further->getID() << " \n";
    5685              :             }
    5686              : #endif
    5687          408 :             further->resetPartialOccupation(this);
    5688          408 :             if (further->getBidiLane() != nullptr
    5689          408 :                     && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5690            0 :                 further->getBidiLane()->resetPartialOccupation(this);
    5691              :             }
    5692              :         }
    5693              :         myFurtherLanes.clear();
    5694              :         myFurtherLanesPosLat.clear();
    5695              :     }
    5696      3121471 : }
    5697              : 
    5698              : 
    5699              : void
    5700      3121010 : MSVehicle::enterLaneAtInsertion(MSLane* enteredLane, double pos, double speed, double posLat, MSMoveReminder::Notification notification) {
    5701      3121010 :     myState = State(pos, speed, posLat, pos - getVehicleType().getLength(), hasDeparted() ? myState.myPreviousSpeed : speed);
    5702      3121010 :     if (myDeparture == NOT_YET_DEPARTED) {
    5703      3049502 :         onDepart();
    5704              :     }
    5705      3121010 :     myCachedPosition = Position::INVALID;
    5706              :     assert(myState.myPos >= 0);
    5707              :     assert(myState.mySpeed >= 0);
    5708      3121010 :     myLane = enteredLane;
    5709      3121010 :     myAmOnNet = true;
    5710              :     // schedule action for the next timestep
    5711      3121010 :     myLastActionTime = MSNet::getInstance()->getCurrentTimeStep() + DELTA_T;
    5712      3121010 :     if (notification != MSMoveReminder::NOTIFICATION_TELEPORT) {
    5713      3110204 :         if (notification == MSMoveReminder::NOTIFICATION_PARKING && myInfluencer != nullptr) {
    5714           13 :             drawOutsideNetwork(false);
    5715              :         }
    5716              :         // set and activate the new lane's reminders, teleports already did that at enterLaneAtMove
    5717      6513751 :         for (std::vector< MSMoveReminder* >::const_iterator rem = enteredLane->getMoveReminders().begin(); rem != enteredLane->getMoveReminders().end(); ++rem) {
    5718      3403547 :             addReminder(*rem);
    5719              :         }
    5720      3110204 :         activateReminders(notification, enteredLane);
    5721              :     } else {
    5722        10806 :         myLastBestLanesEdge = nullptr;
    5723        10806 :         myLastBestLanesInternalLane = nullptr;
    5724        10806 :         myLaneChangeModel->resetState();
    5725        11764 :         while (!myStops.empty() && myStops.front().edge == myCurrEdge && &myStops.front().lane->getEdge() == &myLane->getEdge()
    5726        11319 :                 && myStops.front().pars.endPos < pos) {
    5727            0 :             WRITE_WARNINGF(TL("Vehicle '%' skips stop on lane '%' time=%."), getID(), myStops.front().lane->getID(),
    5728              :                            time2string(MSNet::getInstance()->getCurrentTimeStep()));
    5729            0 :             myStops.pop_front();
    5730              :         }
    5731              :         // avoid startup-effects after teleport
    5732        10806 :         myTimeSinceStartup = getCarFollowModel().getStartupDelay() + DELTA_T;
    5733              : 
    5734              :     }
    5735      3121008 :     computeFurtherLanes(enteredLane, pos);
    5736      3121008 :     if (MSGlobals::gLateralResolution > 0) {
    5737       499466 :         myLaneChangeModel->updateShadowLane();
    5738       499466 :         myLaneChangeModel->updateTargetLane();
    5739      2621542 :     } else if (MSGlobals::gLaneChangeDuration > 0) {
    5740        34035 :         myLaneChangeModel->updateShadowLane();
    5741              :     }
    5742      3121008 :     if (notification != MSMoveReminder::NOTIFICATION_LOAD_STATE) {
    5743      3119427 :         myAngle = computeAngle();
    5744      3119427 :         if (myLaneChangeModel->isOpposite()) {
    5745        21666 :             myAngle += M_PI;
    5746              :         }
    5747              :     }
    5748      3121008 :     if (MSNet::getInstance()->hasPersons()) {
    5749        65251 :         for (MSLane* further : myFurtherLanes) {
    5750          745 :             if (further->mustCheckJunctionCollisions()) {
    5751            4 :                 MSNet::getInstance()->getEdgeControl().checkCollisionForInactive(further);
    5752              :             }
    5753              :         }
    5754              :     }
    5755      3121008 : }
    5756              : 
    5757              : 
    5758              : void
    5759     21849080 : MSVehicle::leaveLane(const MSMoveReminder::Notification reason, const MSLane* approachedLane) {
    5760     60960835 :     for (MoveReminderCont::iterator rem = myMoveReminders.begin(); rem != myMoveReminders.end();) {
    5761     39111755 :         if (rem->first->notifyLeave(*this, myState.myPos + rem->second, reason, approachedLane)) {
    5762              : #ifdef _DEBUG
    5763              :             if (myTraceMoveReminders) {
    5764              :                 traceMoveReminder("notifyLeave", rem->first, rem->second, true);
    5765              :             }
    5766              : #endif
    5767              :             ++rem;
    5768              :         } else {
    5769              : #ifdef _DEBUG
    5770              :             if (myTraceMoveReminders) {
    5771              :                 traceMoveReminder("notifyLeave", rem->first, rem->second, false);
    5772              :             }
    5773              : #endif
    5774              :             rem = myMoveReminders.erase(rem);
    5775              :         }
    5776              :     }
    5777     21849080 :     if ((reason == MSMoveReminder::NOTIFICATION_JUNCTION
    5778     21849080 :             || reason == MSMoveReminder::NOTIFICATION_TELEPORT
    5779      4080835 :             || reason == MSMoveReminder::NOTIFICATION_TELEPORT_CONTINUATION)
    5780     17774142 :             && myLane != nullptr) {
    5781     17774112 :         myOdometer += getLane()->getLength();
    5782              :     }
    5783     21849050 :     if (myLane != nullptr && myLane->getBidiLane() != nullptr && myAmOnNet
    5784     21889678 :             && (!isRailway(getVClass()) || (myLane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5785        18248 :         myLane->getBidiLane()->resetPartialOccupation(this);
    5786              :     }
    5787     21849080 :     if (reason != MSMoveReminder::NOTIFICATION_JUNCTION && reason != MSMoveReminder::NOTIFICATION_LANE_CHANGE) {
    5788              :         // @note. In case of lane change, myFurtherLanes and partial occupation
    5789              :         // are handled in enterLaneAtLaneChange()
    5790      3007671 :         for (MSLane* further : myFurtherLanes) {
    5791              : #ifdef DEBUG_FURTHER
    5792              :             if (DEBUG_COND) {
    5793              :                 std::cout << SIMTIME << " leaveLane \n";
    5794              :             }
    5795              : #endif
    5796        28981 :             further->resetPartialOccupation(this);
    5797        28981 :             if (further->getBidiLane() != nullptr
    5798        28981 :                     && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5799            0 :                 further->getBidiLane()->resetPartialOccupation(this);
    5800              :             }
    5801              :         }
    5802              :         myFurtherLanes.clear();
    5803              :         myFurtherLanesPosLat.clear();
    5804              :     }
    5805      2978690 :     if (reason >= MSMoveReminder::NOTIFICATION_TELEPORT) {
    5806      2978690 :         myAmOnNet = false;
    5807      2978690 :         myWaitingTime = 0;
    5808              :     }
    5809     21849080 :     if (reason != MSMoveReminder::NOTIFICATION_PARKING && resumeFromStopping()) {
    5810          542 :         myStopDist = std::numeric_limits<double>::max();
    5811          542 :         if (myPastStops.back().speed <= 0) {
    5812          972 :             WRITE_WARNINGF(TL("Vehicle '%' aborts stop."), getID());
    5813              :         }
    5814              :     }
    5815     21849080 :     if (reason != MSMoveReminder::NOTIFICATION_PARKING && reason != MSMoveReminder::NOTIFICATION_LANE_CHANGE) {
    5816     20720982 :         while (!myStops.empty() && myStops.front().edge == myCurrEdge && &myStops.front().lane->getEdge() == &myLane->getEdge()) {
    5817          971 :             if (myStops.front().getSpeed() <= 0) {
    5818         1962 :                 WRITE_WARNINGF(TL("Vehicle '%' skips stop on lane '%' time=%."), getID(), myStops.front().lane->getID(),
    5819              :                                time2string(MSNet::getInstance()->getCurrentTimeStep()))
    5820          654 :                 if (MSStopOut::active()) {
    5821              :                     // clean up if stopBlocked was called
    5822            6 :                     MSStopOut::getInstance()->stopNotStarted(this);
    5823              :                 }
    5824          654 :                 myStops.pop_front();
    5825              :             } else {
    5826              :                 MSStop& stop = myStops.front();
    5827              :                 // passed waypoint at the end of the lane
    5828          317 :                 if (!stop.reached) {
    5829          317 :                     if (MSStopOut::active()) {
    5830           12 :                         MSStopOut::getInstance()->stopStarted(this, getPersonNumber(), getContainerNumber(), MSNet::getInstance()->getCurrentTimeStep());
    5831              :                     }
    5832          317 :                     stop.reached = true;
    5833              :                     // enter stopping place so leaveFrom works as expected
    5834          317 :                     if (stop.busstop != nullptr) {
    5835              :                         // let the bus stop know the vehicle
    5836           25 :                         stop.busstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    5837              :                     }
    5838          317 :                     if (stop.containerstop != nullptr) {
    5839              :                         // let the container stop know the vehicle
    5840           13 :                         stop.containerstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    5841              :                     }
    5842              :                     // do not enter parkingarea!
    5843          317 :                     if (stop.chargingStation != nullptr) {
    5844              :                         // let the container stop know the vehicle
    5845          121 :                         stop.chargingStation->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    5846              :                     }
    5847              :                 }
    5848          317 :                 resumeFromStopping();
    5849              :             }
    5850          971 :             myStopDist = std::numeric_limits<double>::max();
    5851              :         }
    5852              :     }
    5853     21849080 : }
    5854              : 
    5855              : 
    5856              : void
    5857        39518 : MSVehicle::leaveLaneBack(const MSMoveReminder::Notification reason, const MSLane* leftLane) {
    5858       161860 :     for (MoveReminderCont::iterator rem = myMoveReminders.begin(); rem != myMoveReminders.end();) {
    5859       122342 :         if (rem->first->notifyLeaveBack(*this, reason, leftLane)) {
    5860              : #ifdef _DEBUG
    5861              :             if (myTraceMoveReminders) {
    5862              :                 traceMoveReminder("notifyLeaveBack", rem->first, rem->second, true);
    5863              :             }
    5864              : #endif
    5865              :             ++rem;
    5866              :         } else {
    5867              : #ifdef _DEBUG
    5868              :             if (myTraceMoveReminders) {
    5869              :                 traceMoveReminder("notifyLeaveBack", rem->first, rem->second, false);
    5870              :             }
    5871              : #endif
    5872              :             rem = myMoveReminders.erase(rem);
    5873              :         }
    5874              :     }
    5875              : #ifdef DEBUG_MOVEREMINDERS
    5876              :     if (DEBUG_COND) {
    5877              :         std::cout << SIMTIME << " veh=" << getID() << " myReminders:";
    5878              :         for (auto rem : myMoveReminders) {
    5879              :             std::cout << rem.first->getDescription() << " ";
    5880              :         }
    5881              :         std::cout << "\n";
    5882              :     }
    5883              : #endif
    5884        39518 : }
    5885              : 
    5886              : 
    5887              : MSAbstractLaneChangeModel&
    5888  10219185726 : MSVehicle::getLaneChangeModel() {
    5889  10219185726 :     return *myLaneChangeModel;
    5890              : }
    5891              : 
    5892              : 
    5893              : const MSAbstractLaneChangeModel&
    5894   4807273385 : MSVehicle::getLaneChangeModel() const {
    5895   4807273385 :     return *myLaneChangeModel;
    5896              : }
    5897              : 
    5898              : bool
    5899       521038 : MSVehicle::isOppositeLane(const MSLane* lane) const {
    5900       521038 :     return (lane->isInternal()
    5901       521038 :             ? & (lane->getLinkCont()[0]->getLane()->getEdge()) != *(myCurrEdge + 1)
    5902       519277 :             : &lane->getEdge() != *myCurrEdge);
    5903              : }
    5904              : 
    5905              : const std::vector<MSVehicle::LaneQ>&
    5906    499638262 : MSVehicle::getBestLanes() const {
    5907    499638262 :     return *myBestLanes.begin();
    5908              : }
    5909              : 
    5910              : 
    5911              : void
    5912   1007220853 : MSVehicle::updateBestLanes(bool forceRebuild, const MSLane* startLane) {
    5913              : #ifdef DEBUG_BESTLANES
    5914              :     if (DEBUG_COND) {
    5915              :         std::cout << SIMTIME << " updateBestLanes veh=" << getID() << " force=" << forceRebuild << " startLane1=" << Named::getIDSecure(startLane) << " myLane=" << Named::getIDSecure(myLane) << "\n";
    5916              :     }
    5917              : #endif
    5918   1007220853 :     if (startLane == nullptr) {
    5919    961591150 :         startLane = myLane;
    5920              :     }
    5921              :     assert(startLane != 0);
    5922   1007220853 :     if (myLaneChangeModel->isOpposite()) {
    5923              :         // depending on the calling context, startLane might be the forward lane
    5924              :         // or the reverse-direction lane. In the latter case we need to
    5925              :         // transform it to the forward lane.
    5926       521038 :         if (isOppositeLane(startLane)) {
    5927              :             // use leftmost lane of forward edge
    5928       111030 :             startLane = startLane->getEdge().getOppositeEdge()->getLanes().back();
    5929              :             assert(startLane != 0);
    5930              : #ifdef DEBUG_BESTLANES
    5931              :             if (DEBUG_COND) {
    5932              :                 std::cout << "   startLaneIsOpposite newStartLane=" << startLane->getID() << "\n";
    5933              :             }
    5934              : #endif
    5935              :         }
    5936              :     }
    5937   1007220853 :     if (forceRebuild) {
    5938      1899724 :         myLastBestLanesEdge = nullptr;
    5939      1899724 :         myLastBestLanesInternalLane = nullptr;
    5940              :     }
    5941   1007220853 :     if (myBestLanes.size() > 0 && !forceRebuild && myLastBestLanesEdge == &startLane->getEdge()) {
    5942    979534397 :         updateOccupancyAndCurrentBestLane(startLane);
    5943              : #ifdef DEBUG_BESTLANES
    5944              :         if (DEBUG_COND) {
    5945              :             std::cout << "  only updateOccupancyAndCurrentBestLane\n";
    5946              :         }
    5947              : #endif
    5948    979534397 :         return;
    5949              :     }
    5950     27686456 :     if (startLane->getEdge().isInternal()) {
    5951     12608379 :         if (myBestLanes.size() == 0 || forceRebuild) {
    5952              :             // rebuilt from previous non-internal lane (may backtrack twice if behind an internal junction)
    5953         2293 :             updateBestLanes(true, startLane->getLogicalPredecessorLane());
    5954              :         }
    5955     12608379 :         if (myLastBestLanesInternalLane == startLane && !forceRebuild) {
    5956              : #ifdef DEBUG_BESTLANES
    5957              :             if (DEBUG_COND) {
    5958              :                 std::cout << "  nothing to do on internal\n";
    5959              :             }
    5960              : #endif
    5961              :             return;
    5962              :         }
    5963              :         // adapt best lanes to fit the current internal edge:
    5964              :         // keep the entries that are reachable from this edge
    5965      4471668 :         const MSEdge* nextEdge = startLane->getNextNormal();
    5966              :         assert(!nextEdge->isInternal());
    5967      8815222 :         for (std::vector<std::vector<LaneQ> >::iterator it = myBestLanes.begin(); it != myBestLanes.end();) {
    5968              :             std::vector<LaneQ>& lanes = *it;
    5969              :             assert(lanes.size() > 0);
    5970      8815222 :             if (&(lanes[0].lane->getEdge()) == nextEdge) {
    5971              :                 // keep those lanes which are successors of internal lanes from the edge of startLane
    5972      4471668 :                 std::vector<LaneQ> oldLanes = lanes;
    5973              :                 lanes.clear();
    5974              :                 const std::vector<MSLane*>& sourceLanes = startLane->getEdge().getLanes();
    5975     10253011 :                 for (std::vector<MSLane*>::const_iterator it_source = sourceLanes.begin(); it_source != sourceLanes.end(); ++it_source) {
    5976      9726803 :                     for (std::vector<LaneQ>::iterator it_lane = oldLanes.begin(); it_lane != oldLanes.end(); ++it_lane) {
    5977      9726803 :                         if ((*it_source)->getLinkCont()[0]->getLane() == (*it_lane).lane) {
    5978      5781343 :                             lanes.push_back(*it_lane);
    5979              :                             break;
    5980              :                         }
    5981              :                     }
    5982              :                 }
    5983              :                 assert(lanes.size() == startLane->getEdge().getLanes().size());
    5984              :                 // patch invalid bestLaneOffset and updated myCurrentLaneInBestLanes
    5985     10253011 :                 for (int i = 0; i < (int)lanes.size(); ++i) {
    5986      5781343 :                     if (i + lanes[i].bestLaneOffset < 0) {
    5987       105946 :                         lanes[i].bestLaneOffset = -i;
    5988              :                     }
    5989      5781343 :                     if (i + lanes[i].bestLaneOffset >= (int)lanes.size()) {
    5990        23457 :                         lanes[i].bestLaneOffset = (int)lanes.size() - i - 1;
    5991              :                     }
    5992              :                     assert(i + lanes[i].bestLaneOffset >= 0);
    5993              :                     assert(i + lanes[i].bestLaneOffset < (int)lanes.size());
    5994      5781343 :                     if (lanes[i].bestContinuations[0] != 0) {
    5995              :                         // patch length of bestContinuation to match expectations (only once)
    5996      5612432 :                         lanes[i].bestContinuations.insert(lanes[i].bestContinuations.begin(), (MSLane*)nullptr);
    5997              :                     }
    5998      5781343 :                     if (startLane->getLinkCont()[0]->getLane() == lanes[i].lane) {
    5999      4512574 :                         myCurrentLaneInBestLanes = lanes.begin() + i;
    6000              :                     }
    6001              :                     assert(&(lanes[i].lane->getEdge()) == nextEdge);
    6002              :                 }
    6003      4471668 :                 myLastBestLanesInternalLane = startLane;
    6004      4471668 :                 updateOccupancyAndCurrentBestLane(startLane);
    6005              : #ifdef DEBUG_BESTLANES
    6006              :                 if (DEBUG_COND) {
    6007              :                     std::cout << "  updated for internal\n";
    6008              :                 }
    6009              : #endif
    6010              :                 return;
    6011      4471668 :             } else {
    6012              :                 // remove passed edges
    6013      4343554 :                 it = myBestLanes.erase(it);
    6014              :             }
    6015              :         }
    6016              :         assert(false); // should always find the next edge
    6017              :     }
    6018              :     // start rebuilding
    6019     15078077 :     myLastBestLanesInternalLane = nullptr;
    6020     15078077 :     myLastBestLanesEdge = &startLane->getEdge();
    6021              :     myBestLanes.clear();
    6022              : 
    6023              :     // get information about the next stop
    6024     15078077 :     MSRouteIterator nextStopEdge = myRoute->end();
    6025              :     const MSLane* nextStopLane = nullptr;
    6026              :     double nextStopPos = 0;
    6027              :     bool nextStopIsWaypoint = false;
    6028     15078077 :     if (!myStops.empty()) {
    6029              :         const MSStop& nextStop = myStops.front();
    6030       239036 :         nextStopLane = nextStop.lane;
    6031       239036 :         if (nextStop.isOpposite) {
    6032              :             // target leftmost lane in forward direction
    6033          340 :             nextStopLane = nextStopLane->getEdge().getOppositeEdge()->getLanes().back();
    6034              :         }
    6035       239036 :         nextStopEdge = nextStop.edge;
    6036       239036 :         nextStopPos = nextStop.pars.startPos;
    6037       239036 :         nextStopIsWaypoint = nextStop.getSpeed() > 0;
    6038              :     }
    6039              :     // myArrivalTime = -1 in the context of validating departSpeed with departLane=best
    6040     15078077 :     if (myParameter->arrivalLaneProcedure >= ArrivalLaneDefinition::GIVEN && nextStopEdge == myRoute->end() && myArrivalLane >= 0) {
    6041       269984 :         nextStopEdge = (myRoute->end() - 1);
    6042       269984 :         nextStopLane = (*nextStopEdge)->getLanes()[myArrivalLane];
    6043       269984 :         nextStopPos = myArrivalPos;
    6044              :     }
    6045     15078077 :     if (nextStopEdge != myRoute->end()) {
    6046              :         // make sure that the "wrong" lanes get a penalty. (penalty needs to be
    6047              :         // large enough to overcome a magic threshold in MSLaneChangeModel::DK2004.cpp:383)
    6048       509020 :         nextStopPos = MAX2(POSITION_EPS, MIN2((double)nextStopPos, (double)(nextStopLane->getLength() - 2 * POSITION_EPS)));
    6049       509020 :         if (nextStopLane->isInternal()) {
    6050              :             // switch to the correct lane before entering the intersection
    6051          171 :             nextStopPos = (*nextStopEdge)->getLength();
    6052              :         }
    6053              :     }
    6054              : 
    6055              :     // go forward along the next lanes;
    6056              :     // trains do not have to deal with lane-changing for stops but their best
    6057              :     // lanes lookahead is needed for rail signal control
    6058     15078077 :     const bool continueAfterStop = nextStopIsWaypoint || isRailway(getVClass());
    6059              :     int seen = 0;
    6060              :     double seenLength = 0;
    6061              :     bool progress = true;
    6062              :     // bestLanes must cover the braking distance even when at the very end of the current lane to avoid unecessary slow down
    6063     30156154 :     const double maxBrakeDist = startLane->getLength() + getCarFollowModel().getHeadwayTime() * getMaxSpeed() + getCarFollowModel().brakeGap(getMaxSpeed()) + getVehicleType().getMinGap();
    6064     15078077 :     const double lookahead = getLaneChangeModel().getStrategicLookahead();
    6065     77590156 :     for (MSRouteIterator ce = myCurrEdge; progress;) {
    6066              :         std::vector<LaneQ> currentLanes;
    6067              :         const std::vector<MSLane*>* allowed = nullptr;
    6068              :         const MSEdge* nextEdge = nullptr;
    6069     62512079 :         if (ce != myRoute->end() && ce + 1 != myRoute->end()) {
    6070     51588946 :             nextEdge = *(ce + 1);
    6071     51588946 :             allowed = (*ce)->allowedLanes(*nextEdge, myType->getVehicleClass());
    6072              :         }
    6073     62512079 :         const std::vector<MSLane*>& lanes = (*ce)->getLanes();
    6074    157767549 :         for (std::vector<MSLane*>::const_iterator i = lanes.begin(); i != lanes.end(); ++i) {
    6075              :             LaneQ q;
    6076     95255470 :             MSLane* cl = *i;
    6077     95255470 :             q.lane = cl;
    6078     95255470 :             q.bestContinuations.push_back(cl);
    6079     95255470 :             q.bestLaneOffset = 0;
    6080     95255470 :             q.length = cl->allowsVehicleClass(myType->getVehicleClass()) ? (*ce)->getLength() : 0;
    6081     95255470 :             q.currentLength = q.length;
    6082              :             // if all lanes are forbidden (i.e. due to a dynamic closing) we want to express no preference
    6083     95255470 :             q.allowsContinuation = allowed == nullptr || std::find(allowed->begin(), allowed->end(), cl) != allowed->end();
    6084     95255470 :             q.occupation = 0;
    6085     95255470 :             q.nextOccupation = 0;
    6086     95255470 :             currentLanes.push_back(q);
    6087              :         }
    6088              :         //
    6089              :         if (nextStopEdge == ce
    6090              :                 // already past the stop edge
    6091     62512079 :                 && !(ce == myCurrEdge && myLane != nullptr && myLane->isInternal())) {
    6092       501769 :             if (!nextStopLane->isInternal() && !continueAfterStop) {
    6093              :                 progress = false;
    6094              :             }
    6095       501769 :             const MSLane* normalStopLane = nextStopLane->getNormalPredecessorLane();
    6096      1618831 :             for (std::vector<LaneQ>::iterator q = currentLanes.begin(); q != currentLanes.end(); ++q) {
    6097      1117062 :                 if (nextStopLane != nullptr && normalStopLane != (*q).lane) {
    6098       615293 :                     (*q).allowsContinuation = false;
    6099       615293 :                     (*q).length = nextStopPos;
    6100       615293 :                     (*q).currentLength = (*q).length;
    6101              :                 }
    6102              :             }
    6103              :         }
    6104              : 
    6105     62512079 :         myBestLanes.push_back(currentLanes);
    6106     62512079 :         ++seen;
    6107     62512079 :         seenLength += currentLanes[0].lane->getLength();
    6108              :         ++ce;
    6109     62512079 :         if (lookahead >= 0) {
    6110           45 :             progress &= (seen <= 2 || seenLength < lookahead); // custom (but we need to look at least one edge ahead)
    6111              :         } else {
    6112     83360466 :             progress &= (seen <= 4 || seenLength < MAX2(maxBrakeDist, 3000.0)); // motorway
    6113     67276347 :             progress &= (seen <= 8 || seenLength < MAX2(maxBrakeDist, 200.0) || isRailway(getVClass()));  // urban
    6114              :         }
    6115     62512079 :         progress &= ce != myRoute->end();
    6116              :         /*
    6117              :         if(progress) {
    6118              :           progress &= (currentLanes.size()!=1||(*ce)->getLanes().size()!=1);
    6119              :         }
    6120              :         */
    6121     62512079 :     }
    6122              : 
    6123              :     // we are examining the last lane explicitly
    6124     15078077 :     if (myBestLanes.size() != 0) {
    6125              :         double bestLength = -1;
    6126              :         // minimum and maximum lane index with best length
    6127              :         int bestThisIndex = 0;
    6128              :         int bestThisMaxIndex = 0;
    6129              :         int index = 0;
    6130              :         std::vector<LaneQ>& last = myBestLanes.back();
    6131     39177959 :         for (std::vector<LaneQ>::iterator j = last.begin(); j != last.end(); ++j, ++index) {
    6132     24099882 :             if ((*j).length > bestLength) {
    6133              :                 bestLength = (*j).length;
    6134              :                 bestThisIndex = index;
    6135              :                 bestThisMaxIndex = index;
    6136      5945396 :             } else if ((*j).length == bestLength) {
    6137              :                 bestThisMaxIndex = index;
    6138              :             }
    6139              :         }
    6140              :         index = 0;
    6141              :         bool requiredChangeRightForbidden = false;
    6142              :         int requireChangeToLeftForbidden = -1;
    6143     39177959 :         for (std::vector<LaneQ>::iterator j = last.begin(); j != last.end(); ++j, ++index) {
    6144     24099882 :             if ((*j).length < bestLength) {
    6145      3491443 :                 if (abs(bestThisIndex - index) < abs(bestThisMaxIndex - index)) {
    6146       124016 :                     (*j).bestLaneOffset = bestThisIndex - index;
    6147              :                 } else {
    6148      3367427 :                     (*j).bestLaneOffset = bestThisMaxIndex - index;
    6149              :                 }
    6150      3491443 :                 if ((*j).bestLaneOffset < 0 && (!(*j).lane->allowsChangingRight(getVClass())
    6151       299722 :                                                 || !(*j).lane->getParallelLane(-1, false)->allowsVehicleClass(getVClass())
    6152       295143 :                                                 || requiredChangeRightForbidden)) {
    6153              :                     // this lane and all further lanes to the left cannot be used
    6154              :                     requiredChangeRightForbidden = true;
    6155         4589 :                     (*j).length = 0;
    6156      3486854 :                 } else if ((*j).bestLaneOffset > 0 && (!(*j).lane->allowsChangingLeft(getVClass())
    6157      3191680 :                                                        || !(*j).lane->getParallelLane(1, false)->allowsVehicleClass(getVClass()))) {
    6158              :                     // this lane and all previous lanes to the right cannot be used
    6159        32127 :                     requireChangeToLeftForbidden = (*j).lane->getIndex();
    6160              :                 }
    6161              :             }
    6162              :         }
    6163     15110259 :         for (int i = requireChangeToLeftForbidden; i >= 0; i--) {
    6164        32182 :             if (last[i].bestLaneOffset > 0) {
    6165        32142 :                 last[i].length = 0;
    6166              :             }
    6167              :         }
    6168              : #ifdef DEBUG_BESTLANES
    6169              :         if (DEBUG_COND) {
    6170              :             std::cout << "   last edge=" << last.front().lane->getEdge().getID() << " (bestIndex=" << bestThisIndex << " bestMaxIndex=" << bestThisMaxIndex << "):\n";
    6171              :             std::vector<LaneQ>& laneQs = myBestLanes.back();
    6172              :             for (std::vector<LaneQ>::iterator j = laneQs.begin(); j != laneQs.end(); ++j) {
    6173              :                 std::cout << "     lane=" << (*j).lane->getID() << " length=" << (*j).length << " bestOffset=" << (*j).bestLaneOffset << "\n";
    6174              :             }
    6175              :         }
    6176              : #endif
    6177              :     }
    6178              :     // go backward through the lanes
    6179              :     // track back best lane and compute the best prior lane(s)
    6180     62512079 :     for (std::vector<std::vector<LaneQ> >::reverse_iterator i = myBestLanes.rbegin() + 1; i != myBestLanes.rend(); ++i) {
    6181              :         std::vector<LaneQ>& nextLanes = (*(i - 1));
    6182              :         std::vector<LaneQ>& clanes = (*i);
    6183     47434002 :         MSEdge* const cE = &clanes[0].lane->getEdge();
    6184              :         int index = 0;
    6185              :         double bestConnectedLength = -1;
    6186              :         double bestLength = -1;
    6187    117988650 :         for (const LaneQ& j : nextLanes) {
    6188    141109296 :             if (j.lane->isApproachedFrom(cE) && bestConnectedLength < j.length) {
    6189              :                 bestConnectedLength = j.length;
    6190              :             }
    6191     70554648 :             if (bestLength < j.length) {
    6192              :                 bestLength = j.length;
    6193              :             }
    6194              :         }
    6195              :         // compute index of the best lane (highest length and least offset from the best next lane)
    6196              :         int bestThisIndex = 0;
    6197              :         int bestThisMaxIndex = 0;
    6198     47434002 :         if (bestConnectedLength > 0) {
    6199              :             index = 0;
    6200    118567652 :             for (LaneQ& j : clanes) {
    6201              :                 const LaneQ* bestConnectedNext = nullptr;
    6202     71141852 :                 if (j.allowsContinuation) {
    6203    170482067 :                     for (const LaneQ& m : nextLanes) {
    6204    117894006 :                         if ((m.lane->allowsVehicleClass(getVClass()) || m.lane->hadPermissionChanges())
    6205    108561365 :                                 && m.lane->isApproachedFrom(cE, j.lane)) {
    6206     63732189 :                             if (betterContinuation(bestConnectedNext, m)) {
    6207              :                                 bestConnectedNext = &m;
    6208              :                             }
    6209              :                         }
    6210              :                     }
    6211     61975952 :                     if (bestConnectedNext != nullptr) {
    6212     61975948 :                         if (bestConnectedNext->length == bestConnectedLength && abs(bestConnectedNext->bestLaneOffset) < 2) {
    6213     60297231 :                             j.length += bestLength;
    6214              :                         } else {
    6215      1678717 :                             j.length += bestConnectedNext->length;
    6216              :                         }
    6217     61975948 :                         j.bestLaneOffset = bestConnectedNext->bestLaneOffset;
    6218              :                     }
    6219              :                 }
    6220     61975948 :                 if (bestConnectedNext != nullptr && (bestConnectedNext->allowsContinuation || bestConnectedNext->length > 0)) {
    6221     61950687 :                     copy(bestConnectedNext->bestContinuations.begin(), bestConnectedNext->bestContinuations.end(), back_inserter(j.bestContinuations));
    6222              :                 } else {
    6223      9191165 :                     j.allowsContinuation = false;
    6224              :                 }
    6225     71141852 :                 if (clanes[bestThisIndex].length < j.length
    6226     64460738 :                         || (clanes[bestThisIndex].length == j.length && abs(clanes[bestThisIndex].bestLaneOffset) > abs(j.bestLaneOffset))
    6227    196021387 :                         || (clanes[bestThisIndex].length == j.length && abs(clanes[bestThisIndex].bestLaneOffset) == abs(j.bestLaneOffset) &&
    6228     60548628 :                             nextLinkPriority(clanes[bestThisIndex].bestContinuations) < nextLinkPriority(j.bestContinuations))
    6229              :                    ) {
    6230              :                     bestThisIndex = index;
    6231              :                     bestThisMaxIndex = index;
    6232     64319131 :                 } else if (clanes[bestThisIndex].length == j.length
    6233     60536979 :                            && abs(clanes[bestThisIndex].bestLaneOffset) == abs(j.bestLaneOffset)
    6234    124855983 :                            && nextLinkPriority(clanes[bestThisIndex].bestContinuations) == nextLinkPriority(j.bestContinuations)) {
    6235              :                     bestThisMaxIndex = index;
    6236              :                 }
    6237     71141852 :                 index++;
    6238              :             }
    6239              : 
    6240              :             //vehicle with elecHybrid device prefers running under an overhead wire
    6241     47425800 :             if (getDevice(typeid(MSDevice_ElecHybrid)) != nullptr) {
    6242              :                 index = 0;
    6243          221 :                 for (const LaneQ& j : clanes) {
    6244          159 :                     std::string overheadWireSegmentID = MSNet::getInstance()->getStoppingPlaceID(j.lane, j.currentLength / 2., SUMO_TAG_OVERHEAD_WIRE_SEGMENT);
    6245          159 :                     if (overheadWireSegmentID != "") {
    6246              :                         bestThisIndex = index;
    6247              :                         bestThisMaxIndex = index;
    6248              :                     }
    6249          159 :                     index++;
    6250              :                 }
    6251              :             }
    6252              : 
    6253              :         } else {
    6254              :             // only needed in case of disconnected routes
    6255              :             int bestNextIndex = 0;
    6256         8202 :             int bestDistToNeeded = (int) clanes.size();
    6257              :             index = 0;
    6258        21938 :             for (std::vector<LaneQ>::iterator j = clanes.begin(); j != clanes.end(); ++j, ++index) {
    6259        13736 :                 if ((*j).allowsContinuation) {
    6260              :                     int nextIndex = 0;
    6261        30304 :                     for (std::vector<LaneQ>::const_iterator m = nextLanes.begin(); m != nextLanes.end(); ++m, ++nextIndex) {
    6262        16766 :                         if ((*m).lane->isApproachedFrom(cE, (*j).lane)) {
    6263         5893 :                             if (bestDistToNeeded > abs((*m).bestLaneOffset)) {
    6264              :                                 bestDistToNeeded = abs((*m).bestLaneOffset);
    6265              :                                 bestThisIndex = index;
    6266              :                                 bestThisMaxIndex = index;
    6267              :                                 bestNextIndex = nextIndex;
    6268              :                             }
    6269              :                         }
    6270              :                     }
    6271              :                 }
    6272              :             }
    6273         8202 :             clanes[bestThisIndex].length += nextLanes[bestNextIndex].length;
    6274         8202 :             copy(nextLanes[bestNextIndex].bestContinuations.begin(), nextLanes[bestNextIndex].bestContinuations.end(), back_inserter(clanes[bestThisIndex].bestContinuations));
    6275              : 
    6276              :         }
    6277              :         // set bestLaneOffset for all lanes
    6278              :         index = 0;
    6279              :         bool requiredChangeRightForbidden = false;
    6280              :         int requireChangeToLeftForbidden = -1;
    6281    118589590 :         for (std::vector<LaneQ>::iterator j = clanes.begin(); j != clanes.end(); ++j, ++index) {
    6282     71155588 :             if ((*j).length < clanes[bestThisIndex].length
    6283     60312894 :                     || ((*j).length == clanes[bestThisIndex].length && abs((*j).bestLaneOffset) > abs(clanes[bestThisIndex].bestLaneOffset))
    6284    131468278 :                     || (nextLinkPriority((*j).bestContinuations)) < nextLinkPriority(clanes[bestThisIndex].bestContinuations)
    6285              :                ) {
    6286     11017967 :                 if (abs(bestThisIndex - index) < abs(bestThisMaxIndex - index)) {
    6287       732342 :                     (*j).bestLaneOffset = bestThisIndex - index;
    6288              :                 } else {
    6289     10285625 :                     (*j).bestLaneOffset = bestThisMaxIndex - index;
    6290              :                 }
    6291     11017967 :                 if ((nextLinkPriority((*j).bestContinuations)) < nextLinkPriority(clanes[bestThisIndex].bestContinuations)) {
    6292              :                     // try to move away from the lower-priority lane before it ends
    6293      9386234 :                     (*j).length = (*j).currentLength;
    6294              :                 }
    6295     11017967 :                 if ((*j).bestLaneOffset < 0 && (!(*j).lane->allowsChangingRight(getVClass())
    6296      3478014 :                                                 || !(*j).lane->getParallelLane(-1, false)->allowsVehicleClass(getVClass())
    6297      3462489 :                                                 || requiredChangeRightForbidden)) {
    6298              :                     // this lane and all further lanes to the left cannot be used
    6299              :                     requiredChangeRightForbidden = true;
    6300        32861 :                     if ((*j).length == (*j).currentLength) {
    6301        29837 :                         (*j).length = 0;
    6302              :                     }
    6303     10985106 :                 } else if ((*j).bestLaneOffset > 0 && (!(*j).lane->allowsChangingLeft(getVClass())
    6304      7483046 :                                                        || !(*j).lane->getParallelLane(1, false)->allowsVehicleClass(getVClass()))) {
    6305              :                     // this lane and all previous lanes to the right cannot be used
    6306        95459 :                     requireChangeToLeftForbidden = (*j).lane->getIndex();
    6307              :                 }
    6308              :             } else {
    6309     60137621 :                 (*j).bestLaneOffset = 0;
    6310              :             }
    6311              :         }
    6312     47538673 :         for (int idx = requireChangeToLeftForbidden; idx >= 0; idx--) {
    6313       104671 :             if (clanes[idx].length == clanes[idx].currentLength) {
    6314        98997 :                 clanes[idx].length = 0;
    6315              :             };
    6316              :         }
    6317              : 
    6318              :         //vehicle with elecHybrid device prefers running under an overhead wire
    6319     47434002 :         if (static_cast<MSDevice_ElecHybrid*>(getDevice(typeid(MSDevice_ElecHybrid))) != 0) {
    6320              :             index = 0;
    6321           62 :             std::string overheadWireID = MSNet::getInstance()->getStoppingPlaceID(clanes[bestThisIndex].lane, (clanes[bestThisIndex].currentLength) / 2, SUMO_TAG_OVERHEAD_WIRE_SEGMENT);
    6322           62 :             if (overheadWireID != "") {
    6323          211 :                 for (std::vector<LaneQ>::iterator j = clanes.begin(); j != clanes.end(); ++j, ++index) {
    6324          153 :                     (*j).bestLaneOffset = bestThisIndex - index;
    6325              :                 }
    6326              :             }
    6327              :         }
    6328              : 
    6329              : #ifdef DEBUG_BESTLANES
    6330              :         if (DEBUG_COND) {
    6331              :             std::cout << "   edge=" << cE->getID() << " (bestIndex=" << bestThisIndex << " bestMaxIndex=" << bestThisMaxIndex << "):\n";
    6332              :             std::vector<LaneQ>& laneQs = clanes;
    6333              :             for (std::vector<LaneQ>::iterator j = laneQs.begin(); j != laneQs.end(); ++j) {
    6334              :                 std::cout << "     lane=" << (*j).lane->getID() << " length=" << (*j).length << " bestOffset=" << (*j).bestLaneOffset << " allowCont=" << (*j).allowsContinuation << "\n";
    6335              :             }
    6336              :         }
    6337              : #endif
    6338              : 
    6339              :     }
    6340     15078077 :     updateOccupancyAndCurrentBestLane(startLane);
    6341              : #ifdef DEBUG_BESTLANES
    6342              :     if (DEBUG_COND) {
    6343              :         std::cout << SIMTIME << " veh=" << getID() << " bestCont=" << toString(getBestLanesContinuation()) << "\n";
    6344              :     }
    6345              : #endif
    6346              : }
    6347              : 
    6348              : void
    6349          250 : MSVehicle::updateLaneBruttoSum() {
    6350          250 :     if (myLane != nullptr) {
    6351          250 :         myLane->markRecalculateBruttoSum();
    6352              :     }
    6353          250 : }
    6354              : 
    6355              : bool
    6356     63732189 : MSVehicle::betterContinuation(const LaneQ* bestConnectedNext, const LaneQ& m) const {
    6357     63732189 :     if (bestConnectedNext == nullptr) {
    6358              :         return true;
    6359      1756241 :     } else if (m.lane->getBidiLane() != nullptr && bestConnectedNext->lane->getBidiLane() == nullptr) {
    6360              :         return false;
    6361      1755503 :     } else if (bestConnectedNext->lane->getBidiLane() != nullptr && m.lane->getBidiLane() == nullptr) {
    6362              :         return true;
    6363      1755503 :     } else if (bestConnectedNext->length < m.length) {
    6364              :         return true;
    6365      1505069 :     } else if (bestConnectedNext->length == m.length) {
    6366      1127267 :         if (abs(bestConnectedNext->bestLaneOffset) > abs(m.bestLaneOffset)) {
    6367              :             return true;
    6368              :         }
    6369      1029512 :         const double contRight = getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_CONTRIGHT, 1);
    6370              :         if (contRight < 1
    6371              :                 // if we don't check for adjacency, the rightmost line will get
    6372              :                 // multiple chances to be better which leads to an uninituitve distribution
    6373         1006 :                 && (m.lane->getIndex() - bestConnectedNext->lane->getIndex()) == 1
    6374      1030291 :                 && RandHelper::rand(getRNG()) > contRight) {
    6375              :             return true;
    6376              :         }
    6377              :     }
    6378              :     return false;
    6379              : }
    6380              : 
    6381              : 
    6382              : int
    6383    384832274 : MSVehicle::nextLinkPriority(const std::vector<MSLane*>& conts) {
    6384    384832274 :     if (conts.size() < 2) {
    6385              :         return -1;
    6386              :     } else {
    6387    352041893 :         const MSLink* const link = conts[0]->getLinkTo(conts[1]);
    6388    352041893 :         if (link != nullptr) {
    6389    352035557 :             return link->havePriority() ? 1 : 0;
    6390              :         } else {
    6391              :             // disconnected route
    6392              :             return -1;
    6393              :         }
    6394              :     }
    6395              : }
    6396              : 
    6397              : 
    6398              : void
    6399    999084142 : MSVehicle::updateOccupancyAndCurrentBestLane(const MSLane* startLane) {
    6400              :     std::vector<LaneQ>& currLanes = *myBestLanes.begin();
    6401              :     std::vector<LaneQ>::iterator i;
    6402   2785108390 :     for (i = currLanes.begin(); i != currLanes.end(); ++i) {
    6403              :         double nextOccupation = 0;
    6404   4212690599 :         for (std::vector<MSLane*>::const_iterator j = (*i).bestContinuations.begin() + 1; j != (*i).bestContinuations.end(); ++j) {
    6405   2426666351 :             nextOccupation += (*j)->getBruttoVehLenSum();
    6406              :         }
    6407   1786024248 :         (*i).nextOccupation = nextOccupation;
    6408              : #ifdef DEBUG_BESTLANES
    6409              :         if (DEBUG_COND) {
    6410              :             std::cout << "     lane=" << (*i).lane->getID() << " nextOccupation=" << nextOccupation << "\n";
    6411              :         }
    6412              : #endif
    6413   1786024248 :         if ((*i).lane == startLane) {
    6414    994612445 :             myCurrentLaneInBestLanes = i;
    6415              :         }
    6416              :     }
    6417    999084142 : }
    6418              : 
    6419              : 
    6420              : const std::vector<MSLane*>&
    6421   1986962139 : MSVehicle::getBestLanesContinuation() const {
    6422   1986962139 :     if (myBestLanes.empty() || myBestLanes[0].empty()) {
    6423              :         return myEmptyLaneVector;
    6424              :     }
    6425   1986962139 :     return (*myCurrentLaneInBestLanes).bestContinuations;
    6426              : }
    6427              : 
    6428              : 
    6429              : const std::vector<MSLane*>&
    6430     64318611 : MSVehicle::getBestLanesContinuation(const MSLane* const l) const {
    6431              :     const MSLane* lane = l;
    6432              :     // XXX: shouldn't this be a "while" to cover more than one internal lane? (Leo) Refs. #2575
    6433     64318611 :     if (lane->getEdge().isInternal()) {
    6434              :         // internal edges are not kept inside the bestLanes structure
    6435      4713097 :         lane = lane->getLinkCont()[0]->getLane();
    6436              :     }
    6437     64318611 :     if (myBestLanes.size() == 0) {
    6438              :         return myEmptyLaneVector;
    6439              :     }
    6440    105513718 :     for (std::vector<LaneQ>::const_iterator i = myBestLanes[0].begin(); i != myBestLanes[0].end(); ++i) {
    6441    105501609 :         if ((*i).lane == lane) {
    6442     64306502 :             return (*i).bestContinuations;
    6443              :         }
    6444              :     }
    6445              :     return myEmptyLaneVector;
    6446              : }
    6447              : 
    6448              : const std::vector<const MSLane*>
    6449       286513 : MSVehicle::getUpcomingLanesUntil(double distance) const {
    6450              :     std::vector<const MSLane*> lanes;
    6451              : 
    6452       286513 :     if (distance <= 0. || hasArrived()) {
    6453              :         // WRITE_WARNINGF(TL("MSVehicle::getUpcomingLanesUntil(): distance ('%') should be greater than 0."), distance);
    6454              :         return lanes;
    6455              :     }
    6456              : 
    6457       286305 :     if (!myLaneChangeModel->isOpposite()) {
    6458       282979 :         distance += getPositionOnLane();
    6459              :     } else {
    6460         3326 :         distance += myLane->getOppositePos(getPositionOnLane());
    6461              :     }
    6462       286305 :     MSLane* lane = myLaneChangeModel->isOpposite() ? myLane->getParallelOpposite() : myLane;
    6463       294342 :     while (lane->isInternal() && (distance > 0.)) {  // include initial internal lanes
    6464         8037 :         lanes.insert(lanes.end(), lane);
    6465         8037 :         distance -= lane->getLength();
    6466        13519 :         lane = lane->getLinkCont().front()->getViaLaneOrLane();
    6467              :     }
    6468              : 
    6469       286305 :     const std::vector<MSLane*>& contLanes = getBestLanesContinuation();
    6470       286305 :     if (contLanes.empty()) {
    6471              :         return lanes;
    6472              :     }
    6473              :     auto contLanesIt = contLanes.begin();
    6474       286305 :     MSRouteIterator routeIt = myCurrEdge;  // keep track of covered edges in myRoute
    6475       613080 :     while (distance > 0.) {
    6476       334586 :         MSLane* l = nullptr;
    6477       334586 :         if (contLanesIt != contLanes.end()) {
    6478       318688 :             l = *contLanesIt;
    6479              :             if (l != nullptr) {
    6480              :                 assert(l->getEdge().getID() == (*routeIt)->getLanes().front()->getEdge().getID());
    6481              :             }
    6482              :             ++contLanesIt;
    6483       318688 :             if (l != nullptr || myLane->isInternal()) {
    6484              :                 ++routeIt;
    6485              :             }
    6486       318688 :             if (l == nullptr) {
    6487         5478 :                 continue;
    6488              :             }
    6489        15898 :         } else if (routeIt != myRoute->end()) {  // bestLanes didn't get us far enough
    6490              :             // choose left-most lane as default (avoid sidewalks, bike lanes etc)
    6491         8976 :             l = (*routeIt)->getLanes().back();
    6492              :             ++routeIt;
    6493              :         } else {  // the search distance goes beyond our route
    6494              :             break;
    6495              :         }
    6496              : 
    6497              :         assert(l != nullptr);
    6498              : 
    6499              :         // insert internal lanes if applicable
    6500       322186 :         const MSLane* internalLane = lanes.size() > 0 ? lanes.back()->getInternalFollowingLane(l) : nullptr;
    6501       366343 :         while ((internalLane != nullptr) && internalLane->isInternal() && (distance > 0.)) {
    6502        44157 :             lanes.insert(lanes.end(), internalLane);
    6503        44157 :             distance -= internalLane->getLength();
    6504        70570 :             internalLane = internalLane->getLinkCont().front()->getViaLaneOrLane();
    6505              :         }
    6506       322186 :         if (distance <= 0.) {
    6507              :             break;
    6508              :         }
    6509              : 
    6510       321297 :         lanes.insert(lanes.end(), l);
    6511       321297 :         distance -= l->getLength();
    6512              :     }
    6513              : 
    6514              :     return lanes;
    6515            0 : }
    6516              : 
    6517              : const std::vector<const MSLane*>
    6518         6689 : MSVehicle::getPastLanesUntil(double distance) const {
    6519              :     std::vector<const MSLane*> lanes;
    6520              : 
    6521         6689 :     if (distance <= 0.) {
    6522              :         // WRITE_WARNINGF(TL("MSVehicle::getPastLanesUntil(): distance ('%') should be greater than 0."), distance);
    6523              :         return lanes;
    6524              :     }
    6525              : 
    6526         6581 :     MSRouteIterator routeIt = myCurrEdge;
    6527         6581 :     if (!myLaneChangeModel->isOpposite()) {
    6528         6557 :         distance += myLane->getLength() - getPositionOnLane();
    6529              :     } else {
    6530           24 :         distance += myLane->getParallelOpposite()->getLength() - myLane->getOppositePos(getPositionOnLane());
    6531              :     }
    6532         6581 :     MSLane* lane = myLaneChangeModel->isOpposite() ? myLane->getParallelOpposite() : myLane;
    6533         6602 :     while (lane->isInternal() && (distance > 0.)) {  // include initial internal lanes
    6534           21 :         lanes.insert(lanes.end(), lane);
    6535           21 :         distance -= lane->getLength();
    6536           21 :         lane = lane->getLogicalPredecessorLane();
    6537              :     }
    6538              : 
    6539        10123 :     while (distance > 0.) {
    6540              :         // choose left-most lane as default (avoid sidewalks, bike lanes etc)
    6541         8789 :         MSLane* l = (*routeIt)->getLanes().back();
    6542              : 
    6543              :         // insert internal lanes if applicable
    6544         8789 :         const MSEdge* internalEdge = lanes.size() > 0 ? (*routeIt)->getInternalFollowingEdge(&(lanes.back()->getEdge()), getVClass()) : nullptr;
    6545         8810 :         const MSLane* internalLane = internalEdge != nullptr ? internalEdge->getLanes().front() : nullptr;
    6546              :         std::vector<const MSLane*> internalLanes;
    6547        11011 :         while ((internalLane != nullptr) && internalLane->isInternal()) {  // collect all internal successor lanes
    6548         2222 :             internalLanes.insert(internalLanes.begin(), internalLane);
    6549         4430 :             internalLane = internalLane->getLinkCont().front()->getViaLaneOrLane();
    6550              :         }
    6551        11011 :         for (auto it = internalLanes.begin(); (it != internalLanes.end()) && (distance > 0.); ++it) {  // check remaining distance in correct order
    6552         2222 :             lanes.insert(lanes.end(), *it);
    6553         2222 :             distance -= (*it)->getLength();
    6554              :         }
    6555         8789 :         if (distance <= 0.) {
    6556              :             break;
    6557              :         }
    6558              : 
    6559         8773 :         lanes.insert(lanes.end(), l);
    6560         8773 :         distance -= l->getLength();
    6561              : 
    6562              :         // NOTE: we're going backwards with the (bi-directional) Iterator
    6563              :         // TODO: consider make reverse_iterator() when moving on to C++14 or later
    6564         8773 :         if (routeIt != myRoute->begin()) {
    6565              :             --routeIt;
    6566              :         } else {  // we went backwards to begin() and already processed the first and final element
    6567              :             break;
    6568              :         }
    6569         8789 :     }
    6570              : 
    6571              :     return lanes;
    6572            0 : }
    6573              : 
    6574              : 
    6575              : const std::vector<MSLane*>
    6576         6353 : MSVehicle::getUpstreamOppositeLanes() const {
    6577         6353 :     const std::vector<const MSLane*> routeLanes = getPastLanesUntil(myLane->getMaximumBrakeDist());
    6578              :     std::vector<MSLane*> result;
    6579        15437 :     for (const MSLane* lane : routeLanes) {
    6580         9855 :         MSLane* opposite = lane->getOpposite();
    6581         9855 :         if (opposite != nullptr) {
    6582         9084 :             result.push_back(opposite);
    6583              :         } else {
    6584              :             break;
    6585              :         }
    6586              :     }
    6587         6353 :     return result;
    6588         6353 : }
    6589              : 
    6590              : 
    6591              : int
    6592    295987967 : MSVehicle::getBestLaneOffset() const {
    6593    295987967 :     if (myBestLanes.empty() || myBestLanes[0].empty()) {
    6594              :         return 0;
    6595              :     } else {
    6596    295433258 :         return (*myCurrentLaneInBestLanes).bestLaneOffset;
    6597              :     }
    6598              : }
    6599              : 
    6600              : double
    6601        19949 : MSVehicle::getBestLaneDist() const {
    6602        19949 :     if (myBestLanes.empty() || myBestLanes[0].empty()) {
    6603              :         return -1;
    6604              :     } else {
    6605        19949 :         return (*myCurrentLaneInBestLanes).length;
    6606              :     }
    6607              : }
    6608              : 
    6609              : 
    6610              : 
    6611              : void
    6612    629238888 : MSVehicle::adaptBestLanesOccupation(int laneIndex, double density) {
    6613              :     std::vector<MSVehicle::LaneQ>& preb = myBestLanes.front();
    6614              :     assert(laneIndex < (int)preb.size());
    6615    629238888 :     preb[laneIndex].occupation = density + preb[laneIndex].nextOccupation;
    6616    629238888 : }
    6617              : 
    6618              : 
    6619              : void
    6620        62886 : MSVehicle::fixPosition() {
    6621        62886 :     if (MSGlobals::gLaneChangeDuration > 0 && !myLaneChangeModel->isChangingLanes()) {
    6622        33628 :         myState.myPosLat = 0;
    6623              :     }
    6624        62886 : }
    6625              : 
    6626              : std::pair<const MSLane*, double>
    6627          255 : MSVehicle::getLanePosAfterDist(double distance) const {
    6628          255 :     if (distance == 0) {
    6629          227 :         return std::make_pair(myLane, getPositionOnLane());
    6630              :     }
    6631           28 :     const std::vector<const MSLane*> lanes = getUpcomingLanesUntil(distance);
    6632           28 :     distance += getPositionOnLane();
    6633           28 :     for (const MSLane* lane : lanes) {
    6634           28 :         if (lane->getLength() > distance) {
    6635              :             return std::make_pair(lane, distance);
    6636              :         }
    6637            0 :         distance -= lane->getLength();
    6638              :     }
    6639            0 :     return std::make_pair(nullptr, -1);
    6640           28 : }
    6641              : 
    6642              : 
    6643              : double
    6644        16920 : MSVehicle::getDistanceToPosition(double destPos, const MSLane* destLane) const {
    6645        16920 :     if (isOnRoad() && destLane != nullptr) {
    6646        16874 :         return myRoute->getDistanceBetween(getPositionOnLane(), destPos, myLane, destLane);
    6647              :     }
    6648              :     return std::numeric_limits<double>::max();
    6649              : }
    6650              : 
    6651              : 
    6652              : std::pair<const MSVehicle* const, double>
    6653     76411359 : MSVehicle::getLeader(double dist, bool considerCrossingFoes) const {
    6654     76411359 :     if (myLane == nullptr) {
    6655            0 :         return std::make_pair(static_cast<const MSVehicle*>(nullptr), -1);
    6656              :     }
    6657     76411359 :     if (dist == 0) {
    6658         2474 :         dist = getCarFollowModel().brakeGap(getSpeed()) + getVehicleType().getMinGap();
    6659              :     }
    6660              :     const MSVehicle* lead = nullptr;
    6661     76411359 :     const MSLane* lane = myLane; // ensure lane does not change between getVehiclesSecure and releaseVehicles;
    6662     76411359 :     const MSLane::VehCont& vehs = lane->getVehiclesSecure();
    6663              :     // vehicle might be outside the road network
    6664     76411359 :     MSLane::VehCont::const_iterator it = std::find(vehs.begin(), vehs.end(), this);
    6665     76411359 :     if (it != vehs.end() && it + 1 != vehs.end()) {
    6666     72698458 :         lead = *(it + 1);
    6667              :     }
    6668     72698458 :     if (lead != nullptr) {
    6669              :         std::pair<const MSVehicle* const, double> result(
    6670     72698458 :             lead, lead->getBackPositionOnLane(myLane) - getPositionOnLane() - getVehicleType().getMinGap());
    6671     72698458 :         lane->releaseVehicles();
    6672     72698458 :         return result;
    6673              :     }
    6674      3712901 :     const double seen = myLane->getLength() - getPositionOnLane();
    6675      3712901 :     const std::vector<MSLane*>& bestLaneConts = getBestLanesContinuation(myLane);
    6676      3712901 :     std::pair<const MSVehicle* const, double> result = myLane->getLeaderOnConsecutive(dist, seen, getSpeed(), *this, bestLaneConts, considerCrossingFoes);
    6677      3712900 :     lane->releaseVehicles();
    6678      3712900 :     return result;
    6679              : }
    6680              : 
    6681              : 
    6682              : std::pair<const MSVehicle* const, double>
    6683      2419056 : MSVehicle::getFollower(double dist) const {
    6684      2419056 :     if (myLane == nullptr) {
    6685            0 :         return std::make_pair(static_cast<const MSVehicle*>(nullptr), -1);
    6686              :     }
    6687      2419056 :     if (dist == 0) {
    6688       748173 :         dist = getCarFollowModel().brakeGap(myLane->getEdge().getSpeedLimit() * 2, 4.5, 0);
    6689              :     }
    6690      2419056 :     return myLane->getFollower(this, getPositionOnLane(), dist, MSLane::MinorLinkMode::FOLLOW_NEVER);
    6691              : }
    6692              : 
    6693              : 
    6694              : double
    6695            0 : MSVehicle::getTimeGapOnLane() const {
    6696              :     // calling getLeader with 0 would induce a dist calculation but we only want to look for the leaders on the current lane
    6697            0 :     std::pair<const MSVehicle* const, double> leaderInfo = getLeader(-1);
    6698            0 :     if (leaderInfo.first == nullptr || getSpeed() == 0) {
    6699            0 :         return -1;
    6700              :     }
    6701            0 :     return (leaderInfo.second + getVehicleType().getMinGap()) / getSpeed();
    6702              : }
    6703              : 
    6704              : 
    6705              : void
    6706      4285993 : MSVehicle::addTransportable(MSTransportable* transportable) {
    6707      4285993 :     MSBaseVehicle::addTransportable(transportable);
    6708        11069 :     if (myStops.size() > 0 && myStops.front().reached) {
    6709         7877 :         if (transportable->isPerson()) {
    6710         7298 :             if (myStops.front().triggered && myStops.front().numExpectedPerson > 0) {
    6711         1503 :                 myStops.front().numExpectedPerson -= (int)myStops.front().pars.awaitedPersons.count(transportable->getID());
    6712              :             }
    6713              :         } else {
    6714          579 :             if (myStops.front().pars.containerTriggered && myStops.front().numExpectedContainer > 0) {
    6715           20 :                 myStops.front().numExpectedContainer -= (int)myStops.front().pars.awaitedContainers.count(transportable->getID());
    6716              :             }
    6717              :         }
    6718              :     }
    6719        11069 : }
    6720              : 
    6721              : 
    6722              : void
    6723    672930356 : MSVehicle::setBlinkerInformation() {
    6724              :     switchOffSignal(VEH_SIGNAL_BLINKER_RIGHT | VEH_SIGNAL_BLINKER_LEFT);
    6725    672930356 :     int state = myLaneChangeModel->getOwnState();
    6726              :     // do not set blinker for sublane changes or when blocked from changing to the right
    6727    672930356 :     const bool blinkerManoeuvre = (((state & LCA_SUBLANE) == 0) && (
    6728    583087171 :                                        (state & LCA_KEEPRIGHT) == 0 || (state & LCA_BLOCKED) == 0));
    6729              :     Signalling left = VEH_SIGNAL_BLINKER_LEFT;
    6730              :     Signalling right = VEH_SIGNAL_BLINKER_RIGHT;
    6731    672930356 :     if (MSGlobals::gLefthand) {
    6732              :         // lane indices increase from left to right
    6733              :         std::swap(left, right);
    6734              :     }
    6735    672930356 :     if ((state & LCA_LEFT) != 0 && blinkerManoeuvre) {
    6736     19402654 :         switchOnSignal(left);
    6737    653527702 :     } else if ((state & LCA_RIGHT) != 0 && blinkerManoeuvre) {
    6738      5591166 :         switchOnSignal(right);
    6739    647936536 :     } else if (myLaneChangeModel->isChangingLanes()) {
    6740       248224 :         if (myLaneChangeModel->getLaneChangeDirection() == 1) {
    6741       159156 :             switchOnSignal(left);
    6742              :         } else {
    6743        89068 :             switchOnSignal(right);
    6744              :         }
    6745              :     } else {
    6746    647688312 :         const MSLane* lane = getLane();
    6747    647688312 :         std::vector<MSLink*>::const_iterator link = MSLane::succLinkSec(*this, 1, *lane, getBestLanesContinuation());
    6748    647688312 :         if (link != lane->getLinkCont().end() && lane->getLength() - getPositionOnLane() < lane->getVehicleMaxSpeed(this) * (double) 7.) {
    6749    153333944 :             switch ((*link)->getDirection()) {
    6750              :                 case LinkDirection::TURN:
    6751              :                 case LinkDirection::LEFT:
    6752              :                 case LinkDirection::PARTLEFT:
    6753              :                     switchOnSignal(VEH_SIGNAL_BLINKER_LEFT);
    6754              :                     break;
    6755              :                 case LinkDirection::RIGHT:
    6756              :                 case LinkDirection::PARTRIGHT:
    6757              :                     switchOnSignal(VEH_SIGNAL_BLINKER_RIGHT);
    6758              :                     break;
    6759              :                 default:
    6760              :                     break;
    6761              :             }
    6762              :         }
    6763              :     }
    6764              :     // stopping related signals
    6765    672930356 :     if (hasStops()
    6766    672930356 :             && (myStops.begin()->reached ||
    6767     14479522 :                 (myStopDist < (myLane->getLength() - getPositionOnLane())
    6768      4901585 :                  && myStopDist < getCarFollowModel().brakeGap(myLane->getVehicleMaxSpeed(this), getCarFollowModel().getMaxDecel(), 3)))) {
    6769     16671343 :         if (myStops.begin()->lane->getIndex() > 0 && myStops.begin()->lane->getParallelLane(-1)->allowsVehicleClass(getVClass())) {
    6770              :             // not stopping on the right. Activate emergency blinkers
    6771              :             switchOnSignal(VEH_SIGNAL_BLINKER_LEFT | VEH_SIGNAL_BLINKER_RIGHT);
    6772     16440022 :         } else if (!myStops.begin()->reached && (myStops.begin()->pars.parking == ParkingType::OFFROAD)) {
    6773              :             // signal upcoming parking stop on the current lane when within braking distance (~2 seconds before braking)
    6774      1493052 :             switchOnSignal(MSGlobals::gLefthand ? VEH_SIGNAL_BLINKER_LEFT : VEH_SIGNAL_BLINKER_RIGHT);
    6775              :         }
    6776              :     }
    6777    672930356 :     if (myInfluencer != nullptr && myInfluencer->getSignals() >= 0) {
    6778           15 :         mySignals = myInfluencer->getSignals();
    6779              :         myInfluencer->setSignals(-1); // overwrite computed signals only once
    6780              :     }
    6781    672930356 : }
    6782              : 
    6783              : void
    6784        85919 : MSVehicle::setEmergencyBlueLight(SUMOTime currentTime) {
    6785              : 
    6786              :     //TODO look if timestep ist SIMSTEP
    6787        85919 :     if (currentTime % 1000 == 0) {
    6788        26126 :         if (signalSet(VEH_SIGNAL_EMERGENCY_BLUE)) {
    6789              :             switchOffSignal(VEH_SIGNAL_EMERGENCY_BLUE);
    6790              :         } else {
    6791              :             switchOnSignal(VEH_SIGNAL_EMERGENCY_BLUE);
    6792              :         }
    6793              :     }
    6794        85919 : }
    6795              : 
    6796              : 
    6797              : int
    6798     21192126 : MSVehicle::getLaneIndex() const {
    6799     21192126 :     return myLane == nullptr ? -1 : myLane->getIndex();
    6800              : }
    6801              : 
    6802              : 
    6803              : void
    6804     13096636 : MSVehicle::setTentativeLaneAndPosition(MSLane* lane, double pos, double posLat) {
    6805     13096636 :     myLane = lane;
    6806     13096636 :     myState.myPos = pos;
    6807     13096636 :     myState.myPosLat = posLat;
    6808     13096636 :     myState.myBackPos = pos - getVehicleType().getLength();
    6809     13096636 : }
    6810              : 
    6811              : 
    6812              : double
    6813    384535320 : MSVehicle::getRightSideOnLane() const {
    6814    384535320 :     return myState.myPosLat + 0.5 * myLane->getWidth() - 0.5 * getVehicleType().getWidth();
    6815              : }
    6816              : 
    6817              : 
    6818              : double
    6819    379257560 : MSVehicle::getLeftSideOnLane() const {
    6820    379257560 :     return myState.myPosLat + 0.5 * myLane->getWidth() + 0.5 * getVehicleType().getWidth();
    6821              : }
    6822              : 
    6823              : 
    6824              : double
    6825    303836318 : MSVehicle::getRightSideOnLane(const MSLane* lane) const {
    6826    303836318 :     return myState.myPosLat + 0.5 * lane->getWidth() - 0.5 * getVehicleType().getWidth();
    6827              : }
    6828              : 
    6829              : 
    6830              : double
    6831    303347706 : MSVehicle::getLeftSideOnLane(const MSLane* lane) const {
    6832    303347706 :     return myState.myPosLat + 0.5 * lane->getWidth() + 0.5 * getVehicleType().getWidth();
    6833              : }
    6834              : 
    6835              : 
    6836              : double
    6837    242364464 : MSVehicle::getRightSideOnEdge(const MSLane* lane) const {
    6838    242364464 :     return getCenterOnEdge(lane) - 0.5 * getVehicleType().getWidth();
    6839              : }
    6840              : 
    6841              : 
    6842              : double
    6843     29636389 : MSVehicle::getLeftSideOnEdge(const MSLane* lane) const {
    6844     29636389 :     return getCenterOnEdge(lane) + 0.5 * getVehicleType().getWidth();
    6845              : }
    6846              : 
    6847              : 
    6848              : double
    6849    710409380 : MSVehicle::getCenterOnEdge(const MSLane* lane) const {
    6850    710409380 :     if (lane == nullptr || &lane->getEdge() == &myLane->getEdge()) {
    6851    709958176 :         return myLane->getRightSideOnEdge() + myState.myPosLat + 0.5 * myLane->getWidth();
    6852       451204 :     } else if (lane == myLaneChangeModel->getShadowLane()) {
    6853        13696 :         if (myLaneChangeModel->isOpposite() && &lane->getEdge() != &myLane->getEdge()) {
    6854        13689 :             return lane->getRightSideOnEdge() + lane->getWidth() - myState.myPosLat + 0.5 * myLane->getWidth();
    6855              :         }
    6856            7 :         if (myLaneChangeModel->getShadowDirection() == -1) {
    6857            0 :             return lane->getRightSideOnEdge() + lane->getWidth() + myState.myPosLat + 0.5 * myLane->getWidth();
    6858              :         } else {
    6859            7 :             return lane->getRightSideOnEdge() - myLane->getWidth() + myState.myPosLat + 0.5 * myLane->getWidth();
    6860              :         }
    6861       437508 :     } else if (lane == myLane->getBidiLane()) {
    6862         1679 :         return lane->getRightSideOnEdge() - myState.myPosLat + 0.5 * lane->getWidth();
    6863              :     } else {
    6864              :         assert(myFurtherLanes.size() == myFurtherLanesPosLat.size());
    6865       509321 :         for (int i = 0; i < (int)myFurtherLanes.size(); ++i) {
    6866       485919 :             if (myFurtherLanes[i] == lane) {
    6867              : #ifdef DEBUG_FURTHER
    6868              :                 if (DEBUG_COND) std::cout << "    getCenterOnEdge veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " furtherLat=" << myFurtherLanesPosLat[i]
    6869              :                                               << " result=" << lane->getRightSideOnEdge() + myFurtherLanesPosLat[i] + 0.5 * lane->getWidth()
    6870              :                                               << "\n";
    6871              : #endif
    6872       412354 :                 return lane->getRightSideOnEdge() + myFurtherLanesPosLat[i] + 0.5 * lane->getWidth();
    6873        73565 :             } else if (myFurtherLanes[i]->getBidiLane() == lane) {
    6874              : #ifdef DEBUG_FURTHER
    6875              :                 if (DEBUG_COND) std::cout << "    getCenterOnEdge veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " furtherLat(bidi)=" << myFurtherLanesPosLat[i]
    6876              :                                               << " result=" << lane->getRightSideOnEdge() + myFurtherLanesPosLat[i] + 0.5 * lane->getWidth()
    6877              :                                               << "\n";
    6878              : #endif
    6879           73 :                 return lane->getRightSideOnEdge() - myFurtherLanesPosLat[i] + 0.5 * lane->getWidth();
    6880              :             }
    6881              :         }
    6882              :         //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myShadowFurtherLanes=" << toString(myLaneChangeModel->getShadowFurtherLanes()) << "\n";
    6883        23402 :         const std::vector<MSLane*>& shadowFurther = myLaneChangeModel->getShadowFurtherLanes();
    6884        23617 :         for (int i = 0; i < (int)shadowFurther.size(); ++i) {
    6885              :             //if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
    6886        23617 :             if (shadowFurther[i] == lane) {
    6887              :                 assert(myLaneChangeModel->getShadowLane() != 0);
    6888        23402 :                 return (lane->getRightSideOnEdge() + myLaneChangeModel->getShadowFurtherLanesPosLat()[i] + 0.5 * lane->getWidth()
    6889        23402 :                         + (myLane->getCenterOnEdge() - myLaneChangeModel->getShadowLane()->getCenterOnEdge()));
    6890              :             }
    6891              :         }
    6892              :         assert(false);
    6893            0 :         throw ProcessError("Request lateral pos of vehicle '" + getID() + "' for invalid lane '" + Named::getIDSecure(lane) + "'");
    6894              :     }
    6895              : }
    6896              : 
    6897              : 
    6898              : double
    6899   3359167368 : MSVehicle::getLatOffset(const MSLane* lane) const {
    6900              :     assert(lane != 0);
    6901   3359167368 :     if (&lane->getEdge() == &myLane->getEdge()) {
    6902   3306507030 :         return myLane->getRightSideOnEdge() - lane->getRightSideOnEdge();
    6903     52660338 :     } else if (myLane->getParallelOpposite() == lane) {
    6904      2172104 :         return (myLane->getWidth() + lane->getWidth()) * 0.5 - 2 * getLateralPositionOnLane();
    6905     50488234 :     } else if (myLane->getBidiLane() == lane) {
    6906       188780 :         return -2 * getLateralPositionOnLane();
    6907              :     } else {
    6908              :         // Check whether the lane is a further lane for the vehicle
    6909     59722066 :         for (int i = 0; i < (int)myFurtherLanes.size(); ++i) {
    6910     58795622 :             if (myFurtherLanes[i] == lane) {
    6911              : #ifdef DEBUG_FURTHER
    6912              :                 if (DEBUG_COND) {
    6913              :                     std::cout << "    getLatOffset veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " posLat=" << myState.myPosLat << " furtherLat=" << myFurtherLanesPosLat[i] << "\n";
    6914              :                 }
    6915              : #endif
    6916     49343585 :                 return myFurtherLanesPosLat[i] - myState.myPosLat;
    6917      9452037 :             } else if (myFurtherLanes[i]->getBidiLane() == lane) {
    6918              : #ifdef DEBUG_FURTHER
    6919              :                 if (DEBUG_COND) {
    6920              :                     std::cout << "    getLatOffset veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " posLat=" << myState.myPosLat << " furtherBidiLat=" << myFurtherLanesPosLat[i] << "\n";
    6921              :                 }
    6922              : #endif
    6923        29425 :                 return -2 * (myFurtherLanesPosLat[i] - myState.myPosLat);
    6924              :             }
    6925              :         }
    6926              : #ifdef DEBUG_FURTHER
    6927              :         if (DEBUG_COND) {
    6928              :             std::cout << SIMTIME << " veh=" << getID() << " myShadowFurtherLanes=" << toString(myLaneChangeModel->getShadowFurtherLanes()) << "\n";
    6929              :         }
    6930              : #endif
    6931              :         // Check whether the lane is a "shadow further lane" for the vehicle
    6932       926444 :         const std::vector<MSLane*>& shadowFurther = myLaneChangeModel->getShadowFurtherLanes();
    6933       938446 :         for (int i = 0; i < (int)shadowFurther.size(); ++i) {
    6934       935953 :             if (shadowFurther[i] == lane) {
    6935              : #ifdef DEBUG_FURTHER
    6936              :                 if (DEBUG_COND) std::cout << "    getLatOffset veh=" << getID()
    6937              :                                               << " shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane())
    6938              :                                               << " lane=" << lane->getID()
    6939              :                                               << " i=" << i
    6940              :                                               << " posLat=" << myState.myPosLat
    6941              :                                               << " shadowPosLat=" << getLatOffset(myLaneChangeModel->getShadowLane())
    6942              :                                               << " shadowFurtherLat=" << myLaneChangeModel->getShadowFurtherLanesPosLat()[i]
    6943              :                                               <<  "\n";
    6944              : #endif
    6945       923951 :                 return getLatOffset(myLaneChangeModel->getShadowLane()) + myLaneChangeModel->getShadowFurtherLanesPosLat()[i] - myState.myPosLat;
    6946              :             }
    6947              :         }
    6948              :         // Check whether the vehicle issued a maneuverReservation on the lane.
    6949              :         const std::vector<MSLane*>& furtherTargets = myLaneChangeModel->getFurtherTargetLanes();
    6950         2934 :         for (int i = 0; i < (int)myFurtherLanes.size(); ++i) {
    6951              :             // Further target lanes are just neighboring lanes of the vehicle's further lanes, @see MSAbstractLaneChangeModel::updateTargetLane()
    6952         2933 :             MSLane* targetLane = furtherTargets[i];
    6953         2933 :             if (targetLane == lane) {
    6954         2492 :                 const double targetDir = myLaneChangeModel->getManeuverDist() < 0 ? -1. : 1.;
    6955         2492 :                 const double latOffset = myFurtherLanesPosLat[i] - myState.myPosLat + targetDir * 0.5 * (myFurtherLanes[i]->getWidth() + targetLane->getWidth());
    6956              : #ifdef DEBUG_TARGET_LANE
    6957              :                 if (DEBUG_COND) {
    6958              :                     std::cout << "    getLatOffset veh=" << getID()
    6959              :                               << " wrt targetLane=" << Named::getIDSecure(myLaneChangeModel->getTargetLane())
    6960              :                               << "\n    i=" << i
    6961              :                               << " posLat=" << myState.myPosLat
    6962              :                               << " furtherPosLat=" << myFurtherLanesPosLat[i]
    6963              :                               << " maneuverDist=" << myLaneChangeModel->getManeuverDist()
    6964              :                               << " targetDir=" << targetDir
    6965              :                               << " latOffset=" << latOffset
    6966              :                               <<  std::endl;
    6967              :                 }
    6968              : #endif
    6969         2492 :                 return latOffset;
    6970              :             }
    6971              :         }
    6972              :         assert(false);
    6973            6 :         throw ProcessError("Request lateral offset of vehicle '" + getID() + "' for invalid lane '" + Named::getIDSecure(lane) + "'");
    6974              :     }
    6975              : }
    6976              : 
    6977              : 
    6978              : double
    6979     35548686 : MSVehicle::lateralDistanceToLane(const int offset) const {
    6980              :     // compute the distance when changing to the neighboring lane
    6981              :     // (ensure we do not lap into the line behind neighLane since there might be unseen blockers)
    6982              :     assert(offset == 0 || offset == 1 || offset == -1);
    6983              :     assert(myLane != nullptr);
    6984              :     assert(myLane->getParallelLane(offset) != nullptr || myLane->getParallelOpposite() != nullptr);
    6985     35548686 :     const double halfCurrentLaneWidth = 0.5 * myLane->getWidth();
    6986     35548686 :     const double halfVehWidth = 0.5 * (getWidth() + NUMERICAL_EPS);
    6987     35548686 :     const double latPos = getLateralPositionOnLane();
    6988     35548686 :     const double oppositeSign = getLaneChangeModel().isOpposite() ? -1 : 1;
    6989     35548686 :     double leftLimit = halfCurrentLaneWidth - halfVehWidth - oppositeSign * latPos;
    6990     35548686 :     double rightLimit = -halfCurrentLaneWidth + halfVehWidth - oppositeSign * latPos;
    6991              :     double latLaneDist = 0;  // minimum distance to move the vehicle fully onto the new lane
    6992     35548686 :     if (offset == 0) {
    6993           10 :         if (latPos + halfVehWidth > halfCurrentLaneWidth) {
    6994              :             // correct overlapping left
    6995            5 :             latLaneDist = halfCurrentLaneWidth - latPos - halfVehWidth;
    6996            5 :         } else if (latPos - halfVehWidth < -halfCurrentLaneWidth) {
    6997              :             // correct overlapping right
    6998            5 :             latLaneDist = -halfCurrentLaneWidth - latPos + halfVehWidth;
    6999              :         }
    7000           10 :         latLaneDist *= oppositeSign;
    7001     35548676 :     } else if (offset == -1) {
    7002     15641279 :         latLaneDist = rightLimit - (getWidth() + NUMERICAL_EPS);
    7003     19907397 :     } else if (offset == 1) {
    7004     19907397 :         latLaneDist = leftLimit + (getWidth() + NUMERICAL_EPS);
    7005              :     }
    7006              : #ifdef DEBUG_ACTIONSTEPS
    7007              :     if (DEBUG_COND) {
    7008              :         std::cout << SIMTIME
    7009              :                   << " veh=" << getID()
    7010              :                   << " halfCurrentLaneWidth=" << halfCurrentLaneWidth
    7011              :                   << " halfVehWidth=" << halfVehWidth
    7012              :                   << " latPos=" << latPos
    7013              :                   << " latLaneDist=" << latLaneDist
    7014              :                   << " leftLimit=" << leftLimit
    7015              :                   << " rightLimit=" << rightLimit
    7016              :                   << "\n";
    7017              :     }
    7018              : #endif
    7019     35548686 :     return latLaneDist;
    7020              : }
    7021              : 
    7022              : 
    7023              : double
    7024   5055560400 : MSVehicle::getLateralOverlap(double posLat, const MSLane* lane) const {
    7025   5055560400 :     return (fabs(posLat) + 0.5 * getVehicleType().getWidth()
    7026   5055560400 :             - 0.5 * lane->getWidth());
    7027              : }
    7028              : 
    7029              : double
    7030            0 : MSVehicle::getLateralOverlap(const MSLane* lane) const {
    7031            0 :     return getLateralOverlap(getLateralPositionOnLane(), lane);
    7032              : }
    7033              : 
    7034              : double
    7035   4868386638 : MSVehicle::getLateralOverlap() const {
    7036   4868386638 :     return getLateralOverlap(getLateralPositionOnLane(), myLane);
    7037              : }
    7038              : 
    7039              : 
    7040              : void
    7041    616189015 : MSVehicle::removeApproachingInformation(const DriveItemVector& lfLinks) const {
    7042   1770949597 :     for (const DriveProcessItem& dpi : lfLinks) {
    7043   1154760582 :         if (dpi.myLink != nullptr) {
    7044    809220194 :             dpi.myLink->removeApproaching(this);
    7045              :         }
    7046              :     }
    7047              :     // unregister on all shadow links
    7048    616189015 :     myLaneChangeModel->removeShadowApproachingInformation();
    7049    616189015 : }
    7050              : 
    7051              : 
    7052              : bool
    7053       800276 : MSVehicle::unsafeLinkAhead(const MSLane* lane, double zipperDist) const {
    7054              :     // the following links are unsafe:
    7055              :     // - zipper links if they are close enough and have approaching vehicles in the relevant time range
    7056              :     // - unprioritized links if the vehicle is currently approaching a prioritzed link and unable to stop in time
    7057       800276 :     double seen = myLane->getLength() - getPositionOnLane();
    7058       800276 :     const double dist = MAX2(zipperDist, getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), 0));
    7059       800276 :     if (seen < dist) {
    7060        70693 :         const std::vector<MSLane*>& bestLaneConts = getBestLanesContinuation(lane);
    7061              :         int view = 1;
    7062        70693 :         std::vector<MSLink*>::const_iterator link = MSLane::succLinkSec(*this, view, *lane, bestLaneConts);
    7063              :         DriveItemVector::const_iterator di = myLFLinkLanes.begin();
    7064       117122 :         while (!lane->isLinkEnd(link) && seen <= dist) {
    7065        70621 :             if ((!lane->isInternal()
    7066        48272 :                     && (((*link)->getState() == LINKSTATE_ZIPPER && seen < (*link)->getFoeVisibilityDistance())
    7067        26078 :                         || !(*link)->havePriority()))
    7068        96519 :                     || (lane->isInternal() && zipperDist > 0)) {
    7069              :                 // find the drive item corresponding to this link
    7070              :                 bool found = false;
    7071        51359 :                 while (di != myLFLinkLanes.end() && !found) {
    7072        26615 :                     if ((*di).myLink != nullptr) {
    7073              :                         const MSLane* diPredLane = (*di).myLink->getLaneBefore();
    7074        26615 :                         if (diPredLane != nullptr) {
    7075        26615 :                             if (&diPredLane->getEdge() == &lane->getEdge()) {
    7076              :                                 found = true;
    7077              :                             }
    7078              :                         }
    7079              :                     }
    7080        26615 :                     if (!found) {
    7081              :                         di++;
    7082              :                     }
    7083              :                 }
    7084        24744 :                 if (found) {
    7085        24744 :                     const SUMOTime leaveTime = (*link)->getLeaveTime((*di).myArrivalTime, (*di).myArrivalSpeed,
    7086        24744 :                                                (*di).getLeaveSpeed(), getVehicleType().getLength());
    7087        24744 :                     const MSLink* entry = (*link)->getCorrespondingEntryLink();
    7088              :                     //if (DEBUG_COND) {
    7089              :                     //    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";
    7090              :                     //}
    7091        24744 :                     if (entry->hasApproachingFoe((*di).myArrivalTime, leaveTime, (*di).myArrivalSpeed, getCarFollowModel().getMaxDecel())) {
    7092              :                         //std::cout << SIMTIME << " veh=" << getID() << " aborting changeTo=" << Named::getIDSecure(bestLaneConts.front()) << " linkState=" << toString((*link)->getState()) << " seen=" << seen << " dist=" << dist << "\n";
    7093              :                         return true;
    7094              :                     }
    7095              :                 }
    7096              :                 // no drive item is found if the vehicle aborts its request within dist
    7097              :             }
    7098        46429 :             lane = (*link)->getViaLaneOrLane();
    7099        46429 :             if (!lane->getEdge().isInternal()) {
    7100        24370 :                 view++;
    7101              :             }
    7102        46429 :             seen += lane->getLength();
    7103        46429 :             link = MSLane::succLinkSec(*this, view, *lane, bestLaneConts);
    7104              :         }
    7105              :     }
    7106              :     return false;
    7107              : }
    7108              : 
    7109              : 
    7110              : PositionVector
    7111      6686724 : MSVehicle::getBoundingBox(double offset) const {
    7112      6686724 :     PositionVector centerLine;
    7113      6686724 :     Position pos = getPosition();
    7114      6686724 :     centerLine.push_back(pos);
    7115      6686724 :     switch (myType->getGuiShape()) {
    7116         1730 :         case SUMOVehicleShape::BUS_FLEXIBLE:
    7117              :         case SUMOVehicleShape::RAIL:
    7118              :         case SUMOVehicleShape::RAIL_CAR:
    7119              :         case SUMOVehicleShape::RAIL_CARGO:
    7120              :         case SUMOVehicleShape::TRUCK_SEMITRAILER:
    7121              :         case SUMOVehicleShape::TRUCK_1TRAILER: {
    7122         4460 :             for (MSLane* lane : myFurtherLanes) {
    7123         2730 :                 centerLine.push_back(lane->getShape().back());
    7124              :             }
    7125              :             break;
    7126              :         }
    7127              :         default:
    7128              :             break;
    7129              :     }
    7130      6686724 :     double l = getLength();
    7131      6686724 :     Position backPos = getBackPosition();
    7132      6686724 :     if (pos.distanceTo2D(backPos) > l + NUMERICAL_EPS) {
    7133              :         // getBackPosition may not match the visual back in networks without internal lanes
    7134       361890 :         double a = getAngle() + M_PI; // angle pointing backwards
    7135       361890 :         backPos = pos + Position(l * cos(a), l * sin(a));
    7136              :     }
    7137      6686724 :     centerLine.push_back(backPos);
    7138      6686724 :     if (offset != 0) {
    7139         6543 :         centerLine.extrapolate2D(offset);
    7140              :     }
    7141              :     PositionVector result = centerLine;
    7142     13369158 :     result.move2side(MAX2(0.0, 0.5 * myType->getWidth() + offset));
    7143     13369158 :     centerLine.move2side(MIN2(0.0, -0.5 * myType->getWidth() - offset));
    7144      6686724 :     result.append(centerLine.reverse(), POSITION_EPS);
    7145      6686724 :     return result;
    7146      6686724 : }
    7147              : 
    7148              : 
    7149              : PositionVector
    7150        73840 : MSVehicle::getBoundingPoly(double offset) const {
    7151        73840 :     switch (myType->getGuiShape()) {
    7152        73356 :         case SUMOVehicleShape::PASSENGER:
    7153              :         case SUMOVehicleShape::PASSENGER_SEDAN:
    7154              :         case SUMOVehicleShape::PASSENGER_HATCHBACK:
    7155              :         case SUMOVehicleShape::PASSENGER_WAGON:
    7156              :         case SUMOVehicleShape::PASSENGER_VAN: {
    7157              :             // box with corners cut off
    7158        73356 :             PositionVector result;
    7159        73356 :             PositionVector centerLine;
    7160        73356 :             centerLine.push_back(getPosition());
    7161        73356 :             centerLine.push_back(getBackPosition());
    7162        73356 :             if (offset != 0) {
    7163         1600 :                 centerLine.extrapolate2D(offset);
    7164              :             }
    7165              :             PositionVector line1 = centerLine;
    7166              :             PositionVector line2 = centerLine;
    7167       146712 :             line1.move2side(MAX2(0.0, 0.3 * myType->getWidth() + offset));
    7168       146712 :             line2.move2side(MAX2(0.0, 0.5 * myType->getWidth() + offset));
    7169        73356 :             line2.scaleRelative(0.8);
    7170        73356 :             result.push_back(line1[0]);
    7171        73356 :             result.push_back(line2[0]);
    7172        73356 :             result.push_back(line2[1]);
    7173        73356 :             result.push_back(line1[1]);
    7174       146712 :             line1.move2side(MIN2(0.0, -0.6 * myType->getWidth() - offset));
    7175       146712 :             line2.move2side(MIN2(0.0, -1.0 * myType->getWidth() - offset));
    7176        73356 :             result.push_back(line1[1]);
    7177        73356 :             result.push_back(line2[1]);
    7178        73356 :             result.push_back(line2[0]);
    7179        73356 :             result.push_back(line1[0]);
    7180              :             return result;
    7181        73356 :         }
    7182          484 :         default:
    7183          484 :             return getBoundingBox();
    7184              :     }
    7185              : }
    7186              : 
    7187              : 
    7188              : bool
    7189       550718 : MSVehicle::onFurtherEdge(const MSEdge* edge) const {
    7190       638198 :     for (std::vector<MSLane*>::const_iterator i = myFurtherLanes.begin(); i != myFurtherLanes.end(); ++i) {
    7191       183168 :         if (&(*i)->getEdge() == edge) {
    7192              :             return true;
    7193              :         }
    7194              :     }
    7195              :     return false;
    7196              : }
    7197              : 
    7198              : 
    7199              : bool
    7200   7642767172 : MSVehicle::isBidiOn(const MSLane* lane) const {
    7201   7643858537 :     return lane->getBidiLane() != nullptr && (
    7202      1091365 :                myLane == lane->getBidiLane()
    7203       550718 :                || onFurtherEdge(&lane->getBidiLane()->getEdge()));
    7204              : }
    7205              : 
    7206              : 
    7207              : bool
    7208           20 : MSVehicle::rerouteParkingArea(const std::string& parkingAreaID, std::string& errorMsg) {
    7209              :     // this function is based on MSTriggeredRerouter::rerouteParkingArea in order to keep
    7210              :     // consistency in the behaviour.
    7211              : 
    7212              :     // get vehicle params
    7213           20 :     MSParkingArea* destParkArea = getNextParkingArea();
    7214           20 :     const MSRoute& route = getRoute();
    7215           20 :     const MSEdge* lastEdge = route.getLastEdge();
    7216              : 
    7217           20 :     if (destParkArea == nullptr) {
    7218              :         // not driving towards a parking area
    7219            0 :         errorMsg = "Vehicle " + getID() + " is not driving to a parking area so it cannot be rerouted.";
    7220            0 :         return false;
    7221              :     }
    7222              : 
    7223              :     // if the current route ends at the parking area, the new route will also and at the new area
    7224           20 :     bool newDestination = (&destParkArea->getLane().getEdge() == route.getLastEdge()
    7225           10 :                            && getArrivalPos() >= destParkArea->getBeginLanePosition()
    7226           30 :                            && getArrivalPos() <= destParkArea->getEndLanePosition());
    7227              : 
    7228              :     // retrieve info on the new parking area
    7229           20 :     MSParkingArea* newParkingArea = (MSParkingArea*) MSNet::getInstance()->getStoppingPlace(
    7230              :                                         parkingAreaID, SumoXMLTag::SUMO_TAG_PARKING_AREA);
    7231              : 
    7232           20 :     if (newParkingArea == nullptr) {
    7233            0 :         errorMsg = "Parking area ID " + toString(parkingAreaID) + " not found in the network.";
    7234            0 :         return false;
    7235              :     }
    7236              : 
    7237           20 :     const MSEdge* newEdge = &(newParkingArea->getLane().getEdge());
    7238           20 :     SUMOAbstractRouter<MSEdge, SUMOVehicle>& router = getRouterTT();
    7239              : 
    7240              :     // Compute the route from the current edge to the parking area edge
    7241              :     ConstMSEdgeVector edgesToPark;
    7242           20 :     router.compute(getEdge(), getPositionOnLane(), newEdge, newParkingArea->getEndLanePosition(), this, MSNet::getInstance()->getCurrentTimeStep(), edgesToPark);
    7243              : 
    7244              :     // Compute the route from the parking area edge to the end of the route
    7245              :     ConstMSEdgeVector edgesFromPark;
    7246           20 :     if (!newDestination) {
    7247           15 :         router.compute(newEdge, lastEdge, this, MSNet::getInstance()->getCurrentTimeStep(), edgesFromPark);
    7248              :     } else {
    7249              :         // adapt plans of any riders
    7250           10 :         for (MSTransportable* p : getPersons()) {
    7251            5 :             p->rerouteParkingArea(getNextParkingArea(), newParkingArea);
    7252              :         }
    7253              :     }
    7254              : 
    7255              :     // we have a new destination, let's replace the vehicle route
    7256           20 :     ConstMSEdgeVector edges = edgesToPark;
    7257           20 :     if (edgesFromPark.size() > 0) {
    7258           15 :         edges.insert(edges.end(), edgesFromPark.begin() + 1, edgesFromPark.end());
    7259              :     }
    7260              : 
    7261           20 :     if (newDestination) {
    7262            5 :         SUMOVehicleParameter* newParameter = new SUMOVehicleParameter();
    7263            5 :         *newParameter = getParameter();
    7264            5 :         newParameter->arrivalPosProcedure = ArrivalPosDefinition::GIVEN;
    7265            5 :         newParameter->arrivalPos = newParkingArea->getEndLanePosition();
    7266            5 :         replaceParameter(newParameter);
    7267              :     }
    7268           20 :     const double routeCost = router.recomputeCosts(edges, this, MSNet::getInstance()->getCurrentTimeStep());
    7269           20 :     ConstMSEdgeVector prevEdges(myCurrEdge, myRoute->end());
    7270           20 :     const double savings = router.recomputeCosts(prevEdges, this, MSNet::getInstance()->getCurrentTimeStep());
    7271           20 :     if (replaceParkingArea(newParkingArea, errorMsg)) {
    7272           20 :         const bool onInit = myLane == nullptr;
    7273           40 :         replaceRouteEdges(edges, routeCost, savings, "TraCI:" + toString(SUMO_TAG_PARKING_AREA_REROUTE), onInit, false, false);
    7274              :     } else {
    7275            0 :         WRITE_WARNING("Vehicle '" + getID() + "' could not reroute to new parkingArea '" + newParkingArea->getID()
    7276              :                       + "' reason=" + errorMsg + ", time=" + time2string(MSNet::getInstance()->getCurrentTimeStep()) + ".");
    7277            0 :         return false;
    7278              :     }
    7279           20 :     return true;
    7280           20 : }
    7281              : 
    7282              : 
    7283              : bool
    7284        45126 : MSVehicle::addTraciStop(SUMOVehicleParameter::Stop stop, std::string& errorMsg) {
    7285        45126 :     const int numStops = (int)myStops.size();
    7286        45126 :     const bool result = MSBaseVehicle::addTraciStop(stop, errorMsg);
    7287        45126 :     if (myLane != nullptr && numStops != (int)myStops.size()) {
    7288        43544 :         updateBestLanes(true);
    7289              :     }
    7290        45126 :     return result;
    7291              : }
    7292              : 
    7293              : 
    7294              : bool
    7295         3345 : MSVehicle::handleCollisionStop(MSStop& stop, const double distToStop) {
    7296         3345 :     if (myCurrEdge == stop.edge && distToStop + POSITION_EPS < getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0)) {
    7297         1552 :         if (distToStop < getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getEmergencyDecel(), 0)) {
    7298         1110 :             double vNew = getCarFollowModel().maximumSafeStopSpeed(distToStop, getCarFollowModel().getMaxDecel(), getSpeed(), false, 0);
    7299              :             //std::cout << SIMTIME << " veh=" << getID() << " v=" << myState.mySpeed << " distToStop=" << distToStop
    7300              :             //    << " vMinNex=" << getCarFollowModel().minNextSpeed(getSpeed(), this)
    7301              :             //    << " bg1=" << getCarFollowModel().brakeGap(myState.mySpeed)
    7302              :             //    << " bg2=" << getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getEmergencyDecel(), 0)
    7303              :             //    << " vNew=" << vNew
    7304              :             //    << "\n";
    7305         1110 :             myState.mySpeed = MIN2(myState.mySpeed, vNew + ACCEL2SPEED(getCarFollowModel().getEmergencyDecel()));
    7306         1110 :             myState.myPos = MIN2(myState.myPos, stop.pars.endPos);
    7307         1110 :             myCachedPosition = Position::INVALID;
    7308         1110 :             if (myState.myPos < myType->getLength()) {
    7309          463 :                 computeFurtherLanes(myLane, myState.myPos, true);
    7310          463 :                 myAngle = computeAngle();
    7311          463 :                 if (myLaneChangeModel->isOpposite()) {
    7312            0 :                     myAngle += M_PI;
    7313              :                 }
    7314              :             }
    7315              :         }
    7316              :     }
    7317         3345 :     return true;
    7318              : }
    7319              : 
    7320              : 
    7321              : bool
    7322     21879980 : MSVehicle::resumeFromStopping() {
    7323     21879980 :     if (isStopped()) {
    7324        46538 :         if (myAmRegisteredAsWaiting) {
    7325          114 :             MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    7326          114 :             myAmRegisteredAsWaiting = false;
    7327              :         }
    7328              :         MSStop& stop = myStops.front();
    7329              :         // we have waited long enough and fulfilled any passenger-requirements
    7330        46538 :         if (stop.busstop != nullptr) {
    7331              :             // inform bus stop about leaving it
    7332        17929 :             stop.busstop->leaveFrom(this);
    7333              :         }
    7334              :         // we have waited long enough and fulfilled any container-requirements
    7335        46538 :         if (stop.containerstop != nullptr) {
    7336              :             // inform container stop about leaving it
    7337          542 :             stop.containerstop->leaveFrom(this);
    7338              :         }
    7339        46538 :         if (stop.parkingarea != nullptr && stop.getSpeed() <= 0) {
    7340              :             // inform parking area about leaving it
    7341         7530 :             stop.parkingarea->leaveFrom(this);
    7342              :         }
    7343        46538 :         if (stop.chargingStation != nullptr) {
    7344              :             // inform charging station about leaving it
    7345         3327 :             stop.chargingStation->leaveFrom(this);
    7346              :         }
    7347              :         // the current stop is no longer valid
    7348        46538 :         myLane->getEdge().removeWaiting(this);
    7349              :         // MSStopOut needs to know whether the stop had a loaded 'ended' value so we call this before replacing the value
    7350        46538 :         if (stop.pars.started == -1) {
    7351              :             // waypoint edge was passed in a single step
    7352          317 :             stop.pars.started = MSNet::getInstance()->getCurrentTimeStep();
    7353              :         }
    7354        46538 :         if (MSStopOut::active()) {
    7355         3657 :             MSStopOut::getInstance()->stopEnded(this, stop.pars, stop.lane->getID());
    7356              :         }
    7357        46538 :         stop.pars.ended = MSNet::getInstance()->getCurrentTimeStep();
    7358       102408 :         for (const auto& rem : myMoveReminders) {
    7359        55870 :             rem.first->notifyStopEnded();
    7360              :         }
    7361        46538 :         if (stop.pars.collision && MSLane::getCollisionAction() == MSLane::COLLISION_ACTION_WARN) {
    7362          458 :             myCollisionImmunity = TIME2STEPS(5); // leave the conflict area
    7363              :         }
    7364        46538 :         if (stop.pars.posLat != INVALID_DOUBLE && MSGlobals::gLateralResolution <= 0) {
    7365              :             // reset lateral position to default
    7366          207 :             myState.myPosLat = 0;
    7367              :         }
    7368        46538 :         myPastStops.push_back(stop.pars);
    7369        46538 :         myPastStops.back().routeIndex = (int)(stop.edge - myRoute->begin());
    7370        46538 :         myStops.pop_front();
    7371        46538 :         myStopDist = std::numeric_limits<double>::max();
    7372              :         // do not count the stopping time towards gridlock time.
    7373              :         // Other outputs use an independent counter and are not affected.
    7374        46538 :         myWaitingTime = 0;
    7375              :         // maybe the next stop is on the same edge; let's rebuild best lanes
    7376        46538 :         updateBestLanes(true);
    7377              :         // continue as wished...
    7378        46538 :         MSNet::getInstance()->informVehicleStateListener(this, MSNet::VehicleState::ENDING_STOP);
    7379        46538 :         MSNet::getInstance()->getVehicleControl().registerStopEnded();
    7380        46538 :         return true;
    7381              :     }
    7382              :     return false;
    7383              : }
    7384              : 
    7385              : 
    7386              : MSVehicle::Influencer&
    7387      4584096 : MSVehicle::getInfluencer() {
    7388      4584096 :     if (myInfluencer == nullptr) {
    7389         3562 :         myInfluencer = new Influencer();
    7390              :     }
    7391      4584096 :     return *myInfluencer;
    7392              : }
    7393              : 
    7394              : MSVehicle::BaseInfluencer&
    7395           24 : MSVehicle::getBaseInfluencer() {
    7396           24 :     return getInfluencer();
    7397              : }
    7398              : 
    7399              : 
    7400              : const MSVehicle::Influencer*
    7401            0 : MSVehicle::getInfluencer() const {
    7402            0 :     return myInfluencer;
    7403              : }
    7404              : 
    7405              : const MSVehicle::BaseInfluencer*
    7406       237678 : MSVehicle::getBaseInfluencer() const {
    7407       237678 :     return myInfluencer;
    7408              : }
    7409              : 
    7410              : 
    7411              : double
    7412         4090 : MSVehicle::getSpeedWithoutTraciInfluence() const {
    7413         4090 :     if (myInfluencer != nullptr && myInfluencer->getOriginalSpeed() >= 0) {
    7414              :         // influencer original speed is -1 on initialization
    7415         1666 :         return myInfluencer->getOriginalSpeed();
    7416              :     }
    7417         2424 :     return myState.mySpeed;
    7418              : }
    7419              : 
    7420              : 
    7421              : int
    7422    976475149 : MSVehicle::influenceChangeDecision(int state) {
    7423    976475149 :     if (hasInfluencer()) {
    7424      2831674 :         state = getInfluencer().influenceChangeDecision(
    7425              :                     MSNet::getInstance()->getCurrentTimeStep(),
    7426      2831674 :                     myLane->getEdge(),
    7427              :                     getLaneIndex(),
    7428              :                     state);
    7429              :     }
    7430    976475149 :     return state;
    7431              : }
    7432              : 
    7433              : 
    7434              : void
    7435         7775 : MSVehicle::setRemoteState(Position xyPos) {
    7436         7775 :     myCachedPosition = xyPos;
    7437         7775 : }
    7438              : 
    7439              : 
    7440              : bool
    7441    765178631 : MSVehicle::isRemoteControlled() const {
    7442    765178631 :     return myInfluencer != nullptr && myInfluencer->isRemoteControlled();
    7443              : }
    7444              : 
    7445              : 
    7446              : bool
    7447        20926 : MSVehicle::wasRemoteControlled(SUMOTime lookBack) const {
    7448        20926 :     return myInfluencer != nullptr && myInfluencer->getLastAccessTimeStep() + lookBack >= MSNet::getInstance()->getCurrentTimeStep();
    7449              : }
    7450              : 
    7451              : 
    7452              : bool
    7453    485646154 : MSVehicle::keepClear(const MSLink* link) const {
    7454    485646154 :     if (link->hasFoes() && link->keepClear() /* && item.myLink->willHaveBlockedFoe()*/) {
    7455    155132870 :         const double keepClearTime = getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_KEEPCLEAR_TIME, -1);
    7456              :         //std::cout << SIMTIME << " veh=" << getID() << " keepClearTime=" << keepClearTime << " accWait=" << getAccumulatedWaitingSeconds() << " keepClear=" << (keepClearTime < 0 || getAccumulatedWaitingSeconds() < keepClearTime) << "\n";
    7457    156555019 :         return keepClearTime < 0 || getAccumulatedWaitingSeconds() < keepClearTime;
    7458              :     } else {
    7459              :         return false;
    7460              :     }
    7461              : }
    7462              : 
    7463              : 
    7464              : bool
    7465    681961191 : MSVehicle::ignoreRed(const MSLink* link, bool canBrake) const {
    7466    681961191 :     if ((myInfluencer != nullptr && !myInfluencer->getEmergencyBrakeRedLight())) {
    7467              :         return true;
    7468              :     }
    7469    681653346 :     const double ignoreRedTime = getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_DRIVE_AFTER_RED_TIME, -1);
    7470              : #ifdef DEBUG_IGNORE_RED
    7471              :     if (DEBUG_COND) {
    7472              :         std::cout << SIMTIME << " veh=" << getID() << " link=" << link->getViaLaneOrLane()->getID() << " state=" << toString(link->getState()) << "\n";
    7473              :     }
    7474              : #endif
    7475    681653346 :     if (ignoreRedTime < 0) {
    7476    681647947 :         const double ignoreYellowTime = getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_DRIVE_AFTER_YELLOW_TIME, 0);
    7477    681647947 :         if (ignoreYellowTime > 0 && link->haveYellow()) {
    7478              :             assert(link->getTLLogic() != 0);
    7479           52 :             const double yellowDuration = STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep() - link->getLastStateChange());
    7480              :             // when activating ignoreYellow behavior, vehicles will drive if they cannot brake
    7481           92 :             return !canBrake || ignoreYellowTime > yellowDuration;
    7482              :         } else {
    7483              :             return false;
    7484              :         }
    7485         5399 :     } else if (link->haveYellow()) {
    7486              :         // always drive at yellow when ignoring red
    7487              :         return true;
    7488         5243 :     } else if (link->haveRed()) {
    7489              :         assert(link->getTLLogic() != 0);
    7490         3832 :         const double redDuration = STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep() - link->getLastStateChange());
    7491              : #ifdef DEBUG_IGNORE_RED
    7492              :         if (DEBUG_COND) {
    7493              :             std::cout
    7494              :             // << SIMTIME << " veh=" << getID() << " link=" << link->getViaLaneOrLane()->getID()
    7495              :                     << "   ignoreRedTime=" << ignoreRedTime
    7496              :                     << " spentRed=" << redDuration
    7497              :                     << " canBrake=" << canBrake << "\n";
    7498              :         }
    7499              : #endif
    7500              :         // when activating ignoreRed behavior, vehicles will always drive if they cannot brake
    7501         6356 :         return !canBrake || ignoreRedTime > redDuration;
    7502              :     } else {
    7503              :         return false;
    7504              :     }
    7505              : }
    7506              : 
    7507              : bool
    7508   1256860538 : MSVehicle::ignoreFoe(const SUMOTrafficObject* foe) const {
    7509   1256860538 :     if (!getParameter().wasSet(VEHPARS_CFMODEL_PARAMS_SET)) {
    7510              :         return false;
    7511              :     }
    7512         2768 :     for (const std::string& typeID : StringTokenizer(getParameter().getParameter(toString(SUMO_ATTR_CF_IGNORE_TYPES), "")).getVector()) {
    7513          398 :         if (typeID == foe->getVehicleType().getID()) {
    7514              :             return true;
    7515              :         }
    7516         1384 :     }
    7517         2381 :     for (const std::string& id : StringTokenizer(getParameter().getParameter(toString(SUMO_ATTR_CF_IGNORE_IDS), "")).getVector()) {
    7518          986 :         if (id == foe->getID()) {
    7519              :             return true;
    7520              :         }
    7521          986 :     }
    7522          409 :     return false;
    7523              : }
    7524              : 
    7525              : bool
    7526    525915010 : MSVehicle::passingMinor() const {
    7527              :     // either on an internal lane that was entered via minor link
    7528              :     // or on approach to minor link below visibility distance
    7529    525915010 :     if (myLane == nullptr) {
    7530              :         return false;
    7531              :     }
    7532    525915010 :     if (myLane->getEdge().isInternal()) {
    7533      8440069 :         return !myLane->getIncomingLanes().front().viaLink->havePriority();
    7534    517474941 :     } else if (myLFLinkLanes.size() > 0 && myLFLinkLanes.front().myLink != nullptr) {
    7535              :         MSLink* link = myLFLinkLanes.front().myLink;
    7536    262803937 :         return !link->havePriority() && myLFLinkLanes.front().myDistance <= link->getFoeVisibilityDistance();
    7537              :     }
    7538              :     return false;
    7539              : }
    7540              : 
    7541              : bool
    7542     20115550 : MSVehicle::isLeader(const MSLink* link, const MSVehicle* veh, const double gap) const {
    7543              :     assert(link->fromInternalLane());
    7544     20115550 :     if (veh == nullptr) {
    7545              :         return false;
    7546              :     }
    7547     20115550 :     if (!myLane->isInternal() || myLane->getEdge().getToJunction() != link->getJunction()) {
    7548              :         // if this vehicle is not yet on the junction, every vehicle is a leader
    7549              :         return true;
    7550              :     }
    7551      1817268 :     if (veh->getLaneChangeModel().hasBlueLight()) {
    7552              :         // blue light device automatically gets right of way
    7553              :         return true;
    7554              :     }
    7555      1817000 :     const MSLane* foeLane = veh->getLane();
    7556      1817000 :     if (foeLane->isInternal()) {
    7557      1349645 :         if (foeLane->getEdge().getFromJunction() == link->getJunction()) {
    7558      1331805 :             SUMOTime egoET = myJunctionConflictEntryTime;
    7559      1331805 :             SUMOTime foeET = veh->myJunctionEntryTime;
    7560              :             // check relationship between link and foeLane
    7561      1331805 :             if (foeLane->getNormalPredecessorLane() == link->getInternalLaneBefore()->getNormalPredecessorLane()) {
    7562              :                 // we are entering the junction from the same lane
    7563       442151 :                 egoET = myJunctionEntryTimeNeverYield;
    7564       442151 :                 foeET = veh->myJunctionEntryTimeNeverYield;
    7565       442151 :                 if (link->isExitLinkAfterInternalJunction() && link->getInternalLaneBefore()->getLogicalPredecessorLane()->getEntryLink()->isIndirect()) {
    7566        91632 :                     egoET = myJunctionConflictEntryTime;
    7567              :                 }
    7568              :             } else {
    7569       889654 :                 const MSLink* foeLink = foeLane->getIncomingLanes()[0].viaLink;
    7570       889654 :                 const MSJunctionLogic* logic = link->getJunction()->getLogic();
    7571              :                 assert(logic != nullptr);
    7572              :                 // determine who has right of way
    7573              :                 bool response; // ego response to foe
    7574              :                 bool response2; // foe response to ego
    7575              :                 // attempt 1: tlLinkState
    7576       889654 :                 const MSLink* entry = link->getCorrespondingEntryLink();
    7577       889654 :                 const MSLink* foeEntry = foeLink->getCorrespondingEntryLink();
    7578       889654 :                 if (entry->haveRed() || foeEntry->haveRed()) {
    7579              :                     // ensure that vehicles which are stuck on the intersection may exit
    7580       117970 :                     if (!foeEntry->haveRed() && veh->getSpeed() > SUMO_const_haltingSpeed && gap < 0) {
    7581              :                         // foe might be oncoming, don't drive unless foe can still brake safely
    7582        12518 :                         const double foeNextSpeed = veh->getSpeed() + ACCEL2SPEED(veh->getCarFollowModel().getMaxAccel());
    7583        12518 :                         const double foeBrakeGap = veh->getCarFollowModel().brakeGap(
    7584        12518 :                                                        foeNextSpeed, veh->getCarFollowModel().getMaxDecel(), veh->getCarFollowModel().getHeadwayTime());
    7585              :                         // the minGap was subtracted from gap in MSLink::getLeaderInfo (enlarging the negative gap)
    7586              :                         // so the -2* makes it point in the right direction
    7587        12518 :                         const double foeGap = -gap - veh->getLength() - 2 * getVehicleType().getMinGap();
    7588              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7589              :                         if (DEBUG_COND) {
    7590              :                             std::cout << " foeGap=" << foeGap << " foeBGap=" << foeBrakeGap << "\n";
    7591              : 
    7592              :                         }
    7593              : #endif
    7594        12518 :                         if (foeGap < foeBrakeGap) {
    7595              :                             response = true;
    7596              :                             response2 = false;
    7597              :                         } else {
    7598              :                             response = false;
    7599              :                             response2 = true;
    7600              :                         }
    7601              :                     } else {
    7602              :                         // let conflict entry time decide
    7603              :                         response = true;
    7604              :                         response2 = true;
    7605              :                     }
    7606       771684 :                 } else if (entry->havePriority() != foeEntry->havePriority()) {
    7607       562137 :                     response = !entry->havePriority();
    7608       562137 :                     response2 = !foeEntry->havePriority();
    7609       209547 :                 } else if (entry->haveYellow() && foeEntry->haveYellow()) {
    7610              :                     // let the faster vehicle keep moving
    7611         5192 :                     response = veh->getSpeed() >= getSpeed();
    7612         5192 :                     response2 = getSpeed() >= veh->getSpeed();
    7613              :                 } else {
    7614              :                     // fallback if pedestrian crossings are involved
    7615       204355 :                     response = logic->getResponseFor(link->getIndex()).test(foeLink->getIndex());
    7616       204355 :                     response2 = logic->getResponseFor(foeLink->getIndex()).test(link->getIndex());
    7617              :                 }
    7618              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7619              :                 if (DEBUG_COND) {
    7620              :                     std::cout << SIMTIME
    7621              :                               << " foeLane=" << foeLane->getID()
    7622              :                               << " foeLink=" << foeLink->getViaLaneOrLane()->getID()
    7623              :                               << " linkIndex=" << link->getIndex()
    7624              :                               << " foeLinkIndex=" << foeLink->getIndex()
    7625              :                               << " entryState=" << toString(entry->getState())
    7626              :                               << " entryState2=" << toString(foeEntry->getState())
    7627              :                               << " response=" << response
    7628              :                               << " response2=" << response2
    7629              :                               << "\n";
    7630              :                 }
    7631              : #endif
    7632       889654 :                 if (!response) {
    7633              :                     // if we have right of way over the foe, entryTime does not matter
    7634        83324 :                     foeET = veh->myJunctionConflictEntryTime;
    7635        83324 :                     egoET = myJunctionEntryTime;
    7636       806330 :                 } else if (response && response2) {
    7637              :                     // in a mutual conflict scenario, use entry time to avoid deadlock
    7638       128784 :                     foeET = veh->myJunctionConflictEntryTime;
    7639       128784 :                     egoET = myJunctionConflictEntryTime;
    7640              :                 }
    7641              :             }
    7642      1331805 :             if (egoET == foeET) {
    7643              :                 // try to use speed as tie braker
    7644       125803 :                 if (getSpeed() == veh->getSpeed()) {
    7645              :                     // use ID as tie braker
    7646              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7647              :                     if (DEBUG_COND) {
    7648              :                         std::cout << SIMTIME << " veh=" << getID() << " equal ET " << egoET << " with foe " << veh->getID()
    7649              :                                   << " foeIsLeaderByID=" << (getID() < veh->getID()) << "\n";
    7650              :                     }
    7651              : #endif
    7652        62728 :                     return getID() < veh->getID();
    7653              :                 } else {
    7654              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7655              :                     if (DEBUG_COND) {
    7656              :                         std::cout << SIMTIME << " veh=" << getID() << " equal ET " << egoET << " with foe " << veh->getID()
    7657              :                                   << " foeIsLeaderBySpeed=" << (getSpeed() < veh->getSpeed())
    7658              :                                   << " v=" << getSpeed() << " foeV=" << veh->getSpeed()
    7659              :                                   << "\n";
    7660              :                     }
    7661              : #endif
    7662        63075 :                     return getSpeed() < veh->getSpeed();
    7663              :                 }
    7664              :             } else {
    7665              :                 // leader was on the junction first
    7666              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7667              :                 if (DEBUG_COND) {
    7668              :                     std::cout << SIMTIME << " veh=" << getID() << " egoET " << egoET << " with foe " << veh->getID()
    7669              :                               << " foeET=" << foeET  << " isLeader=" << (egoET > foeET) << "\n";
    7670              :                 }
    7671              : #endif
    7672      1206002 :                 return egoET > foeET;
    7673              :             }
    7674              :         } else {
    7675              :             // vehicle can only be partially on the junction. Must be a leader
    7676              :             return true;
    7677              :         }
    7678              :     } else {
    7679              :         // vehicle can only be partially on the junction. Must be a leader
    7680              :         return true;
    7681              :     }
    7682              : }
    7683              : 
    7684              : void
    7685         2479 : MSVehicle::saveState(OutputDevice& out) {
    7686         2479 :     MSBaseVehicle::saveState(out);
    7687              :     // here starts the vehicle internal part (see loading)
    7688              :     std::vector<std::string> internals;
    7689         2479 :     internals.push_back(toString(myParameter->parametersSet));
    7690         2479 :     internals.push_back(toString(myDeparture));
    7691         2479 :     internals.push_back(toString(distance(myRoute->begin(), myCurrEdge)));
    7692         2479 :     internals.push_back(toString(myDepartPos));
    7693         2479 :     internals.push_back(toString(myWaitingTime));
    7694         2479 :     internals.push_back(toString(myTimeLoss));
    7695         2479 :     internals.push_back(toString(myLastActionTime));
    7696         2479 :     internals.push_back(toString(isStopped()));
    7697         2479 :     internals.push_back(toString(myPastStops.size()));
    7698         2479 :     out.writeAttr(SUMO_ATTR_STATE, internals);
    7699         2479 :     out.writeAttr(SUMO_ATTR_POSITION, std::vector<double> { myState.myPos, myState.myBackPos, myState.myLastCoveredDist });
    7700         2479 :     out.writeAttr(SUMO_ATTR_SPEED, std::vector<double> { myState.mySpeed, myState.myPreviousSpeed });
    7701         2479 :     out.writeAttr(SUMO_ATTR_ANGLE, GeomHelper::naviDegree(myAngle));
    7702         2479 :     out.writeAttr(SUMO_ATTR_POSITION_LAT, myState.myPosLat);
    7703         2479 :     out.writeAttr(SUMO_ATTR_WAITINGTIME, myWaitingTimeCollector.getState());
    7704         2479 :     myLaneChangeModel->saveState(out);
    7705              :     // save past stops
    7706         5445 :     for (SUMOVehicleParameter::Stop stop : myPastStops) {
    7707         2966 :         stop.write(out, false);
    7708              :         // do not write started and ended twice
    7709         2966 :         if ((stop.parametersSet & STOP_STARTED_SET) == 0) {
    7710         5922 :             out.writeAttr(SUMO_ATTR_STARTED, time2string(stop.started));
    7711              :         }
    7712         2966 :         if ((stop.parametersSet & STOP_ENDED_SET) == 0) {
    7713         5922 :             out.writeAttr(SUMO_ATTR_ENDED, time2string(stop.ended));
    7714              :         }
    7715         2966 :         stop.writeParams(out);
    7716         2966 :         out.closeTag();
    7717         2966 :     }
    7718              :     // save upcoming stops
    7719         2947 :     for (MSStop& stop : myStops) {
    7720          468 :         stop.write(out);
    7721              :     }
    7722              :     // save parameters and device states
    7723         2479 :     myParameter->writeParams(out);
    7724         6257 :     for (MSVehicleDevice* const dev : myDevices) {
    7725         3778 :         dev->saveState(out);
    7726              :     }
    7727         2479 :     out.closeTag();
    7728         2479 : }
    7729              : 
    7730              : void
    7731         4160 : MSVehicle::loadState(const SUMOSAXAttributes& attrs, const SUMOTime offset) {
    7732         4160 :     if (!attrs.hasAttribute(SUMO_ATTR_POSITION)) {
    7733            0 :         throw ProcessError(TL("Error: Invalid vehicles in state (may be a meso state)!"));
    7734              :     }
    7735              :     int routeOffset;
    7736              :     bool stopped;
    7737              :     int pastStops;
    7738              : 
    7739         4160 :     std::istringstream bis(attrs.getString(SUMO_ATTR_STATE));
    7740         4160 :     bis >> myParameter->parametersSet;
    7741         4160 :     bis >> myDeparture;
    7742         4160 :     bis >> routeOffset;
    7743         4160 :     bis >> myDepartPos;
    7744         4160 :     bis >> myWaitingTime;
    7745         4160 :     bis >> myTimeLoss;
    7746         4160 :     bis >> myLastActionTime;
    7747              :     bis >> stopped;
    7748         4160 :     bis >> pastStops;
    7749              : 
    7750         4160 :     if (attrs.hasAttribute(SUMO_ATTR_ARRIVALPOS_RANDOMIZED)) {
    7751              :         bool ok;
    7752            4 :         myArrivalPos = attrs.get<double>(SUMO_ATTR_ARRIVALPOS_RANDOMIZED, getID().c_str(), ok);
    7753              :     }
    7754              :     // load stops
    7755              :     myStops.clear();
    7756         4160 :     addStops(!MSGlobals::gCheckRoutes, &myCurrEdge, false);
    7757              : 
    7758         4160 :     if (hasDeparted()) {
    7759         1784 :         myCurrEdge = myRoute->begin() + routeOffset;
    7760         1784 :         myDeparture -= offset;
    7761              :         // fix stops
    7762         4724 :         while (pastStops > 0) {
    7763         2940 :             myPastStops.push_back(myStops.front().pars);
    7764         2940 :             myPastStops.back().routeIndex = (int)(myStops.front().edge - myRoute->begin());
    7765         2940 :             myStops.pop_front();
    7766         2940 :             pastStops--;
    7767              :         }
    7768              :         // see MSBaseVehicle constructor
    7769         1784 :         if (myParameter->wasSet(VEHPARS_FORCE_REROUTE)) {
    7770         1385 :             calculateArrivalParams(true);
    7771              :         }
    7772              :         // a (tentative lane is needed for calling hasArrivedInternal
    7773         1784 :         myLane = (*myCurrEdge)->getLanes()[0];
    7774              :     }
    7775         4160 :     if (getActionStepLength() == DELTA_T && !isActionStep(SIMSTEP)) {
    7776            1 :         myLastActionTime -= (myLastActionTime - SIMSTEP) % DELTA_T;
    7777            3 :         WRITE_WARNINGF(TL("Action steps are out of sync for loaded vehicle '%'."), getID());
    7778              :     }
    7779         4160 :     std::istringstream pis(attrs.getString(SUMO_ATTR_POSITION));
    7780         4160 :     pis >> myState.myPos >> myState.myBackPos >> myState.myLastCoveredDist;
    7781         4160 :     std::istringstream sis(attrs.getString(SUMO_ATTR_SPEED));
    7782         4160 :     sis >> myState.mySpeed >> myState.myPreviousSpeed;
    7783         4160 :     myAcceleration = SPEED2ACCEL(myState.mySpeed - myState.myPreviousSpeed);
    7784         4160 :     myAngle = GeomHelper::fromNaviDegree(attrs.getFloat(SUMO_ATTR_ANGLE));
    7785         4160 :     myState.myPosLat = attrs.getFloat(SUMO_ATTR_POSITION_LAT);
    7786         4160 :     std::istringstream dis(attrs.getString(SUMO_ATTR_DISTANCE));
    7787         4160 :     dis >> myOdometer >> myNumberReroutes;
    7788         4160 :     myWaitingTimeCollector.setState(attrs.getString(SUMO_ATTR_WAITINGTIME));
    7789         4160 :     if (stopped) {
    7790          211 :         myStops.front().startedFromState = true;
    7791          211 :         myStopDist = 0;
    7792              :     }
    7793         4160 :     myLaneChangeModel->loadState(attrs);
    7794              :     // no need to reset myCachedPosition here since state loading happens directly after creation
    7795         4160 : }
    7796              : 
    7797              : void
    7798           32 : MSVehicle::loadPreviousApproaching(MSLink* link, bool setRequest,
    7799              :                                    SUMOTime arrivalTime, double arrivalSpeed,
    7800              :                                    double arrivalSpeedBraking,
    7801              :                                    double dist, double leaveSpeed) {
    7802              :     // ensure that approach information is reset on the next call to setApproachingForAllLinks
    7803           32 :     myLFLinkLanes.push_back(DriveProcessItem(link, 0, 0, setRequest,
    7804              :                             arrivalTime, arrivalSpeed, arrivalSpeedBraking, dist, leaveSpeed));
    7805              : 
    7806           32 : }
    7807              : 
    7808              : 
    7809              : std::shared_ptr<MSSimpleDriverState>
    7810      2437146 : MSVehicle::getDriverState() const {
    7811      2437146 :     return myDriverState->getDriverState();
    7812              : }
    7813              : 
    7814              : 
    7815              : double
    7816    598551164 : MSVehicle::getFriction() const {
    7817    598551164 :     return myFrictionDevice == nullptr ? 1. : myFrictionDevice->getMeasuredFriction();
    7818              : }
    7819              : 
    7820              : 
    7821              : void
    7822          241 : MSVehicle::setPreviousSpeed(double prevSpeed, double prevAcceleration) {
    7823          241 :     myState.mySpeed = MAX2(0., prevSpeed);
    7824              :     // also retcon acceleration
    7825          241 :     if (prevAcceleration != std::numeric_limits<double>::min()) {
    7826            8 :         myAcceleration = prevAcceleration;
    7827              :     } else {
    7828          233 :         myAcceleration = SPEED2ACCEL(myState.mySpeed - myState.myPreviousSpeed);
    7829              :     }
    7830          241 : }
    7831              : 
    7832              : 
    7833              : double
    7834   1783171208 : MSVehicle::getCurrentApparentDecel() const {
    7835              :     //return MAX2(-myAcceleration, getCarFollowModel().getApparentDecel());
    7836   1783171208 :     return getCarFollowModel().getApparentDecel();
    7837              : }
    7838              : 
    7839              : /****************************************************************************/
    7840              : bool
    7841           32 : MSVehicle::setExitManoeuvre() {
    7842           32 :     return (myManoeuvre.configureExitManoeuvre(this));
    7843              : }
    7844              : 
    7845              : /* -------------------------------------------------------------------------
    7846              :  * methods of MSVehicle::manoeuvre
    7847              :  * ----------------------------------------------------------------------- */
    7848              : 
    7849      4638859 : MSVehicle::Manoeuvre::Manoeuvre() : myManoeuvreStop(""), myManoeuvreStartTime(0), myManoeuvreCompleteTime(0), myManoeuvreType(MSVehicle::MANOEUVRE_NONE), myGUIIncrement(0) {}
    7850              : 
    7851              : 
    7852            0 : MSVehicle::Manoeuvre::Manoeuvre(const Manoeuvre& manoeuvre) {
    7853            0 :     myManoeuvreStop = manoeuvre.myManoeuvreStop;
    7854            0 :     myManoeuvreStartTime = manoeuvre.myManoeuvreStartTime;
    7855            0 :     myManoeuvreCompleteTime = manoeuvre.myManoeuvreCompleteTime;
    7856            0 :     myManoeuvreType = manoeuvre.myManoeuvreType;
    7857            0 :     myGUIIncrement = manoeuvre.myGUIIncrement;
    7858            0 : }
    7859              : 
    7860              : 
    7861              : MSVehicle::Manoeuvre&
    7862            0 : MSVehicle::Manoeuvre::operator=(const Manoeuvre& manoeuvre) {
    7863            0 :     myManoeuvreStop = manoeuvre.myManoeuvreStop;
    7864            0 :     myManoeuvreStartTime = manoeuvre.myManoeuvreStartTime;
    7865            0 :     myManoeuvreCompleteTime = manoeuvre.myManoeuvreCompleteTime;
    7866            0 :     myManoeuvreType = manoeuvre.myManoeuvreType;
    7867            0 :     myGUIIncrement = manoeuvre.myGUIIncrement;
    7868            0 :     return *this;
    7869              : }
    7870              : 
    7871              : 
    7872              : bool
    7873            0 : MSVehicle::Manoeuvre::operator!=(const Manoeuvre& manoeuvre) {
    7874            0 :     return (myManoeuvreStop != manoeuvre.myManoeuvreStop ||
    7875            0 :             myManoeuvreStartTime != manoeuvre.myManoeuvreStartTime ||
    7876            0 :             myManoeuvreCompleteTime != manoeuvre.myManoeuvreCompleteTime ||
    7877            0 :             myManoeuvreType != manoeuvre.myManoeuvreType ||
    7878            0 :             myGUIIncrement != manoeuvre.myGUIIncrement
    7879            0 :            );
    7880              : }
    7881              : 
    7882              : 
    7883              : double
    7884          450 : MSVehicle::Manoeuvre::getGUIIncrement() const {
    7885          450 :     return (myGUIIncrement);
    7886              : }
    7887              : 
    7888              : 
    7889              : MSVehicle::ManoeuvreType
    7890         2971 : MSVehicle::Manoeuvre::getManoeuvreType() const {
    7891         2971 :     return (myManoeuvreType);
    7892              : }
    7893              : 
    7894              : 
    7895              : MSVehicle::ManoeuvreType
    7896         2971 : MSVehicle::getManoeuvreType() const {
    7897         2971 :     return (myManoeuvre.getManoeuvreType());
    7898              : }
    7899              : 
    7900              : 
    7901              : void
    7902           30 : MSVehicle::setManoeuvreType(const MSVehicle::ManoeuvreType mType) {
    7903           30 :     myManoeuvre.setManoeuvreType(mType);
    7904           30 : }
    7905              : 
    7906              : 
    7907              : void
    7908           30 : MSVehicle::Manoeuvre::setManoeuvreType(const MSVehicle::ManoeuvreType mType) {
    7909           30 :     myManoeuvreType = mType;
    7910           30 : }
    7911              : 
    7912              : 
    7913              : bool
    7914           30 : MSVehicle::Manoeuvre::configureEntryManoeuvre(MSVehicle* veh) {
    7915           30 :     if (!veh->hasStops()) {
    7916              :         return false;    // should never happen - checked before call
    7917              :     }
    7918              : 
    7919           30 :     const SUMOTime currentTime = MSNet::getInstance()->getCurrentTimeStep();
    7920           30 :     const MSStop& stop = veh->getNextStop();
    7921              : 
    7922           30 :     int manoeuverAngle = stop.parkingarea->getLastFreeLotAngle();
    7923           30 :     double GUIAngle = stop.parkingarea->getLastFreeLotGUIAngle();
    7924           30 :     if (abs(GUIAngle) < 0.1) {
    7925              :         GUIAngle = -0.1;    // Wiggle vehicle on parallel entry
    7926              :     }
    7927           30 :     myManoeuvreVehicleID = veh->getID();
    7928           30 :     myManoeuvreStop = stop.parkingarea->getID();
    7929           30 :     myManoeuvreType = MSVehicle::MANOEUVRE_ENTRY;
    7930           30 :     myManoeuvreStartTime = currentTime;
    7931           30 :     myManoeuvreCompleteTime = currentTime + veh->myType->getEntryManoeuvreTime(manoeuverAngle);
    7932           30 :     myGUIIncrement = GUIAngle / (STEPS2TIME(myManoeuvreCompleteTime - myManoeuvreStartTime) / TS);
    7933              : 
    7934              : #ifdef DEBUG_STOPS
    7935              :     if (veh->isSelected()) {
    7936              :         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 <<
    7937              :                   " endTime=" << myManoeuvreCompleteTime << " manoeuvre time=" << myManoeuvreCompleteTime - currentTime << " parkArea=" << myManoeuvreStop << std::endl;
    7938              :     }
    7939              : #endif
    7940              : 
    7941           30 :     return (true);
    7942              : }
    7943              : 
    7944              : 
    7945              : bool
    7946           32 : MSVehicle::Manoeuvre::configureExitManoeuvre(MSVehicle* veh) {
    7947              :     // At the moment we only want to set for parking areas
    7948           32 :     if (!veh->hasStops()) {
    7949              :         return true;
    7950              :     }
    7951           32 :     if (veh->getNextStop().parkingarea == nullptr) {
    7952              :         return true;
    7953              :     }
    7954              : 
    7955           30 :     if (myManoeuvreType != MSVehicle::MANOEUVRE_NONE) {
    7956              :         return (false);
    7957              :     }
    7958              : 
    7959           30 :     const SUMOTime currentTime = MSNet::getInstance()->getCurrentTimeStep();
    7960              : 
    7961           30 :     int manoeuverAngle = veh->getCurrentParkingArea()->getManoeuverAngle(*veh);
    7962           30 :     double GUIAngle = veh->getCurrentParkingArea()->getGUIAngle(*veh);
    7963           30 :     if (abs(GUIAngle) < 0.1) {
    7964              :         GUIAngle = 0.1;    // Wiggle vehicle on parallel exit
    7965              :     }
    7966              : 
    7967           30 :     myManoeuvreVehicleID = veh->getID();
    7968           30 :     myManoeuvreStop = veh->getCurrentParkingArea()->getID();
    7969           30 :     myManoeuvreType = MSVehicle::MANOEUVRE_EXIT;
    7970           30 :     myManoeuvreStartTime = currentTime;
    7971           30 :     myManoeuvreCompleteTime = currentTime + veh->myType->getExitManoeuvreTime(manoeuverAngle);
    7972           30 :     myGUIIncrement = -GUIAngle / (STEPS2TIME(myManoeuvreCompleteTime - myManoeuvreStartTime) / TS);
    7973           30 :     if (veh->remainingStopDuration() > 0) {
    7974           20 :         myManoeuvreCompleteTime += veh->remainingStopDuration();
    7975              :     }
    7976              : 
    7977              : #ifdef DEBUG_STOPS
    7978              :     if (veh->isSelected()) {
    7979              :         std::cout << "EXIT manoeuvre start: vehicle=" << veh->getID() << " Manoeuvre Angle=" << manoeuverAngle  << " increment=" << RAD2DEG(myGUIIncrement) << " currentTime=" << currentTime
    7980              :                   << " endTime=" << myManoeuvreCompleteTime << " manoeuvre time=" << myManoeuvreCompleteTime - currentTime << " parkArea=" << myManoeuvreStop << std::endl;
    7981              :     }
    7982              : #endif
    7983              : 
    7984              :     return (true);
    7985              : }
    7986              : 
    7987              : 
    7988              : bool
    7989          222 : MSVehicle::Manoeuvre::entryManoeuvreIsComplete(MSVehicle* veh) {
    7990              :     // At the moment we only want to consider parking areas - need to check because we could be setting up a manoeuvre
    7991          222 :     if (!veh->hasStops()) {
    7992              :         return (true);
    7993              :     }
    7994              :     MSStop* currentStop = &veh->myStops.front();
    7995          222 :     if (currentStop->parkingarea == nullptr) {
    7996              :         return true;
    7997          220 :     } else if (currentStop->parkingarea->getID() != myManoeuvreStop || MSVehicle::MANOEUVRE_ENTRY != myManoeuvreType) {
    7998           30 :         if (configureEntryManoeuvre(veh)) {
    7999           30 :             MSNet::getInstance()->informVehicleStateListener(veh, MSNet::VehicleState::MANEUVERING);
    8000           30 :             return (false);
    8001              :         } else { // cannot configure entry so stop trying
    8002              :             return true;
    8003              :         }
    8004          190 :     } else if (MSNet::getInstance()->getCurrentTimeStep() < myManoeuvreCompleteTime) {
    8005              :         return false;
    8006              :     } else { // manoeuvre complete
    8007           30 :         myManoeuvreType = MSVehicle::MANOEUVRE_NONE;
    8008           30 :         return true;
    8009              :     }
    8010              : }
    8011              : 
    8012              : 
    8013              : bool
    8014            0 : MSVehicle::Manoeuvre::manoeuvreIsComplete(const ManoeuvreType checkType) const {
    8015            0 :     if (checkType != myManoeuvreType) {
    8016              :         return true;    // we're not maneuvering / wrong manoeuvre
    8017              :     }
    8018              : 
    8019            0 :     if (MSNet::getInstance()->getCurrentTimeStep() < myManoeuvreCompleteTime) {
    8020              :         return false;
    8021              :     } else {
    8022              :         return true;
    8023              :     }
    8024              : }
    8025              : 
    8026              : 
    8027              : bool
    8028         6266 : MSVehicle::Manoeuvre::manoeuvreIsComplete() const {
    8029         6266 :     return (MSNet::getInstance()->getCurrentTimeStep() >= myManoeuvreCompleteTime);
    8030              : }
    8031              : 
    8032              : 
    8033              : bool
    8034         6266 : MSVehicle::manoeuvreIsComplete() const {
    8035         6266 :     return (myManoeuvre.manoeuvreIsComplete());
    8036              : }
    8037              : 
    8038              : 
    8039              : std::pair<double, double>
    8040         7058 : MSVehicle::estimateTimeToNextStop() const {
    8041         7058 :     if (hasStops()) {
    8042         7058 :         MSLane* lane = myLane;
    8043         7058 :         if (lane == nullptr) {
    8044              :             // not in network
    8045           84 :             lane = getEdge()->getLanes()[0];
    8046              :         }
    8047              :         const MSStop& stop = myStops.front();
    8048              :         auto it = myCurrEdge + 1;
    8049              :         // drive to end of current edge
    8050         7058 :         double dist = (lane->getLength() - getPositionOnLane());
    8051         7058 :         double travelTime = lane->getEdge().getMinimumTravelTime(this) * dist / lane->getLength();
    8052              :         // drive until stop edge
    8053         8414 :         while (it != myRoute->end() && it < stop.edge) {
    8054         1356 :             travelTime += (*it)->getMinimumTravelTime(this);
    8055         1356 :             dist += (*it)->getLength();
    8056              :             it++;
    8057              :         }
    8058              :         // drive up to the stop position
    8059         7058 :         const double stopEdgeDist = stop.pars.endPos - (lane == stop.lane ? lane->getLength() : 0);
    8060         7058 :         dist += stopEdgeDist;
    8061         7058 :         travelTime += stop.lane->getEdge().getMinimumTravelTime(this) * (stopEdgeDist / stop.lane->getLength());
    8062              :         // estimate time loss due to acceleration and deceleration
    8063              :         // maximum speed is limited by available distance:
    8064              :         const double a = getCarFollowModel().getMaxAccel();
    8065              :         const double b = getCarFollowModel().getMaxDecel();
    8066         7058 :         const double c = getSpeed();
    8067              :         const double d = dist;
    8068         7058 :         const double len = getVehicleType().getLength();
    8069         7058 :         const double vs = MIN2(MAX2(stop.getSpeed(), 0.0), stop.lane->getVehicleMaxSpeed(this));
    8070              :         // distAccel = (v - c)^2 / (2a)
    8071              :         // distDecel = (v + vs)*(v - vs) / 2b = (v^2 - vs^2) / (2b)
    8072              :         // distAccel + distDecel < d
    8073         7058 :         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))))
    8074        13848 :                                             + pow((a * vs), 2))))) * 0.5) + (c * b)) / (b + a));
    8075         7058 :         it = myCurrEdge;
    8076              :         double v0 = c;
    8077         7058 :         bool v0Stable = getAcceleration() == 0 && v0 > 0;
    8078              :         double timeLossAccel = 0;
    8079              :         double timeLossDecel = 0;
    8080              :         double timeLossLength = 0;
    8081        16848 :         while (it != myRoute->end() && it <= stop.edge) {
    8082         9790 :             double v = MIN2(maxVD, (*it)->getVehicleMaxSpeed(this));
    8083         9790 :             double edgeLength = (it == stop.edge ? stop.pars.endPos : (*it)->getLength()) - (it == myCurrEdge ? getPositionOnLane() : 0);
    8084         9790 :             if (edgeLength <= len && v0Stable && v0 < v) {
    8085              :                 const double lengthDist = MIN2(len, edgeLength);
    8086           20 :                 const double dTL = lengthDist / v0 - lengthDist / v;
    8087              :                 //std::cout << "   e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " el=" << edgeLength << " lDist=" << lengthDist << " newTLL=" << dTL<< "\n";
    8088           20 :                 timeLossLength += dTL;
    8089              :             }
    8090         9790 :             if (edgeLength > len) {
    8091         8698 :                 const double dv = v - v0;
    8092         8698 :                 if (dv > 0) {
    8093              :                     // timeLossAccel = timeAccel - timeMaxspeed = dv / a - distAccel / v
    8094         6350 :                     const double dTA = dv / a - dv * (v + v0) / (2 * a * v);
    8095              :                     //std::cout << "   e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLA=" << dTA << "\n";
    8096         6350 :                     timeLossAccel += dTA;
    8097              :                     // time loss from vehicle length
    8098         2348 :                 } else if (dv < 0) {
    8099              :                     // timeLossDecel = timeDecel - timeMaxspeed = dv / b - distDecel / v
    8100          540 :                     const double dTD = -dv / b + dv * (v + v0) / (2 * b * v0);
    8101              :                     //std::cout << "   e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLD=" << dTD << "\n";
    8102          540 :                     timeLossDecel += dTD;
    8103              :                 }
    8104              :                 v0 = v;
    8105              :                 v0Stable = true;
    8106              :             }
    8107              :             it++;
    8108              :         }
    8109              :         // final deceleration to stop (may also be acceleration or deceleration to waypoint speed)
    8110              :         double v = vs;
    8111         7058 :         const double dv = v - v0;
    8112         7058 :         if (dv > 0) {
    8113              :             // timeLossAccel = timeAccel - timeMaxspeed = dv / a - distAccel / v
    8114          144 :             const double dTA = dv / a - dv * (v + v0) / (2 * a * v);
    8115              :             //std::cout << "  final e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLA=" << dTA << "\n";
    8116          144 :             timeLossAccel += dTA;
    8117              :             // time loss from vehicle length
    8118         6914 :         } else if (dv < 0) {
    8119              :             // timeLossDecel = timeDecel - timeMaxspeed = dv / b - distDecel / v
    8120         6890 :             const double dTD = -dv / b + dv * (v + v0) / (2 * b * v0);
    8121              :             //std::cout << "  final  e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLD=" << dTD << "\n";
    8122         6890 :             timeLossDecel += dTD;
    8123              :         }
    8124         7058 :         const double result = travelTime + timeLossAccel + timeLossDecel + timeLossLength;
    8125              :         //std::cout << SIMTIME << " v=" << c << " a=" << a << " b=" << b << " maxVD=" << maxVD << " tt=" << travelTime
    8126              :         //    << " ta=" << timeLossAccel << " td=" << timeLossDecel << " tl=" << timeLossLength << " res=" << result << "\n";
    8127         7058 :         return {MAX2(0.0, result), dist};
    8128              :     } else {
    8129            0 :         return {INVALID_DOUBLE, INVALID_DOUBLE};
    8130              :     }
    8131              : }
    8132              : 
    8133              : 
    8134              : double
    8135         1675 : MSVehicle::getStopDelay() const {
    8136         1675 :     if (hasStops() && myStops.front().pars.until >= 0) {
    8137              :         const MSStop& stop = myStops.front();
    8138         1392 :         SUMOTime estimatedDepart = MSNet::getInstance()->getCurrentTimeStep() - DELTA_T;
    8139         1392 :         if (stop.reached) {
    8140          732 :             return STEPS2TIME(estimatedDepart + stop.duration - stop.pars.until);
    8141              :         }
    8142          660 :         if (stop.pars.duration > 0) {
    8143          588 :             estimatedDepart += stop.pars.duration;
    8144              :         }
    8145          660 :         estimatedDepart += TIME2STEPS(estimateTimeToNextStop().first);
    8146          660 :         const double result = MAX2(0.0, STEPS2TIME(estimatedDepart - stop.pars.until));
    8147          660 :         return result;
    8148              :     } else {
    8149              :         // vehicles cannot drive before 'until' so stop delay can never be
    8150              :         // negative and we can use -1 to signal "undefined"
    8151              :         return -1;
    8152              :     }
    8153              : }
    8154              : 
    8155              : 
    8156              : double
    8157         5430 : MSVehicle::getStopArrivalDelay() const {
    8158         5430 :     if (hasStops() && myStops.front().pars.arrival >= 0) {
    8159              :         const MSStop& stop = myStops.front();
    8160         4252 :         if (stop.reached) {
    8161         1304 :             return STEPS2TIME(stop.pars.started - stop.pars.arrival);
    8162              :         } else {
    8163         2948 :             return STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep()) + estimateTimeToNextStop().first - STEPS2TIME(stop.pars.arrival);
    8164              :         }
    8165              :     } else {
    8166              :         // vehicles can arrival earlier than planned so arrival delay can be negative
    8167              :         return INVALID_DOUBLE;
    8168              :     }
    8169              : }
    8170              : 
    8171              : 
    8172              : const MSEdge*
    8173   2962988126 : MSVehicle::getCurrentEdge() const {
    8174   2962988126 :     return myLane != nullptr ? &myLane->getEdge() : getEdge();
    8175              : }
    8176              : 
    8177              : 
    8178              : const MSEdge*
    8179         3896 : MSVehicle::getNextEdgePtr() const {
    8180         3896 :     if (myLane == nullptr || (myCurrEdge + 1) == myRoute->end()) {
    8181            8 :         return nullptr;
    8182              :     }
    8183         3888 :     if (myLane->isInternal()) {
    8184          568 :         return &myLane->getCanonicalSuccessorLane()->getEdge();
    8185              :     } else {
    8186         3320 :         const MSEdge* nextNormal = succEdge(1);
    8187         3320 :         const MSEdge* nextInternal = myLane->getEdge().getInternalFollowingEdge(nextNormal, getVClass());
    8188         3320 :         return nextInternal ? nextInternal : nextNormal;
    8189              :     }
    8190              : }
    8191              : 
    8192              : 
    8193              : const MSLane*
    8194         1591 : MSVehicle::getPreviousLane(const MSLane* current, int& furtherIndex) const {
    8195         1591 :     if (furtherIndex < (int)myFurtherLanes.size()) {
    8196         1214 :         return myFurtherLanes[furtherIndex++];
    8197              :     } else {
    8198              :         // try to use route information
    8199          377 :         int routeIndex = getRoutePosition();
    8200              :         bool resultInternal;
    8201          377 :         if (MSGlobals::gUsingInternalLanes && MSNet::getInstance()->hasInternalLinks()) {
    8202            0 :             if (myLane->isInternal()) {
    8203            0 :                 if (furtherIndex % 2 == 0) {
    8204            0 :                     routeIndex -= (furtherIndex + 0) / 2;
    8205              :                     resultInternal = false;
    8206              :                 } else {
    8207            0 :                     routeIndex -= (furtherIndex + 1) / 2;
    8208              :                     resultInternal = false;
    8209              :                 }
    8210              :             } else {
    8211            0 :                 if (furtherIndex % 2 != 0) {
    8212            0 :                     routeIndex -= (furtherIndex + 1) / 2;
    8213              :                     resultInternal = false;
    8214              :                 } else {
    8215            0 :                     routeIndex -= (furtherIndex + 2) / 2;
    8216              :                     resultInternal = true;
    8217              :                 }
    8218              :             }
    8219              :         } else {
    8220          377 :             routeIndex -= furtherIndex;
    8221              :             resultInternal = false;
    8222              :         }
    8223          377 :         furtherIndex++;
    8224          377 :         if (routeIndex >= 0) {
    8225          163 :             if (resultInternal) {
    8226            0 :                 const MSEdge* prevNormal = myRoute->getEdges()[routeIndex];
    8227            0 :                 for (MSLane* cand : prevNormal->getLanes()) {
    8228            0 :                     for (MSLink* link : cand->getLinkCont()) {
    8229            0 :                         if (link->getLane() == current) {
    8230            0 :                             if (link->getViaLane() != nullptr) {
    8231              :                                 return link->getViaLane();
    8232              :                             } else {
    8233            0 :                                 return const_cast<MSLane*>(link->getLaneBefore());
    8234              :                             }
    8235              :                         }
    8236              :                     }
    8237              :                 }
    8238              :             } else {
    8239          163 :                 return myRoute->getEdges()[routeIndex]->getLanes()[0];
    8240              :             }
    8241              :         }
    8242              :     }
    8243              :     return current;
    8244              : }
    8245              : 
    8246              : SUMOTime
    8247   1433286680 : MSVehicle::getWaitingTimeFor(const MSLink* link) const {
    8248              :     // this vehicle currently has the highest priority on the allway_stop
    8249   1433286680 :     return link == myHaveStoppedFor ? SUMOTime_MAX : getWaitingTime();
    8250              : }
    8251              : 
    8252              : 
    8253              : void
    8254          715 : MSVehicle::resetApproachOnReroute() {
    8255              :     bool diverged = false;
    8256              :     const ConstMSEdgeVector& route = myRoute->getEdges();
    8257          715 :     int ri = getRoutePosition();
    8258         3122 :     for (const DriveProcessItem& dpi : myLFLinkLanes) {
    8259         2407 :         if (dpi.myLink != nullptr) {
    8260         2404 :             if (!diverged) {
    8261         2161 :                 const MSEdge* next = route[ri + 1];
    8262         2161 :                 if (&dpi.myLink->getLane()->getEdge() != next) {
    8263              :                     diverged = true;
    8264              :                 } else {
    8265         2094 :                     if (dpi.myLink->getViaLane() == nullptr) {
    8266              :                         ri++;
    8267              :                     }
    8268              :                 }
    8269              :             }
    8270              :             if (diverged) {
    8271          310 :                 dpi.myLink->removeApproaching(this);
    8272              :             }
    8273              :         }
    8274              :     }
    8275          715 : }
    8276              : 
    8277              : /****************************************************************************/
        

Generated by: LCOV version 2.0-1