LCOV - code coverage report
Current view: top level - src/microsim - MSVehicle.cpp (source / functions) Coverage Total Hit
Test: lcov.info Lines: 96.3 % 3312 3191
Test Date: 2026-04-16 16:39:47 Functions: 95.1 % 225 214

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

Generated by: LCOV version 2.0-1