LCOV - code coverage report
Current view: top level - src/microsim/trigger - MSTriggeredRerouter.cpp (source / functions) Coverage Total Hit
Test: lcov.info Lines: 92.4 % 616 569
Test Date: 2026-10-12 15:53:19 Functions: 94.3 % 35 33

            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    MSTriggeredRerouter.cpp
      15              : /// @author  Daniel Krajzewicz
      16              : /// @author  Jakob Erdmann
      17              : /// @author  Michael Behrisch
      18              : /// @author  Mirco Sturari
      19              : /// @author  Mirko Barthauer
      20              : /// @date    Mon, 25 July 2005
      21              : ///
      22              : // Reroutes vehicles passing an edge
      23              : /****************************************************************************/
      24              : #include <config.h>
      25              : 
      26              : #include <string>
      27              : #include <algorithm>
      28              : #ifdef HAVE_FOX
      29              : #include <utils/common/ScopedLocker.h>
      30              : #endif
      31              : #include <utils/options/OptionsCont.h>
      32              : #include <utils/common/MsgHandler.h>
      33              : #include <utils/common/Command.h>
      34              : #include <utils/xml/SUMOXMLDefinitions.h>
      35              : #include <utils/common/UtilExceptions.h>
      36              : #include <utils/common/ToString.h>
      37              : #include <utils/common/StringUtils.h>
      38              : #include <utils/xml/SUMOSAXHandler.h>
      39              : #include <utils/router/DijkstraRouter.h>
      40              : #include <utils/common/RandHelper.h>
      41              : #include <utils/common/WrappingCommand.h>
      42              : #include <libsumo/TraCIConstants.h>
      43              : #include <microsim/MSEdgeWeightsStorage.h>
      44              : #include <microsim/MSLane.h>
      45              : #include <microsim/MSLink.h>
      46              : #include <microsim/MSVehicle.h>
      47              : #include <microsim/MSBaseVehicle.h>
      48              : #include <microsim/MSRoute.h>
      49              : #include <microsim/MSEdge.h>
      50              : #include <microsim/MSEventControl.h>
      51              : #include <microsim/MSNet.h>
      52              : #include <microsim/MSVehicleControl.h>
      53              : #include <microsim/MSGlobals.h>
      54              : #include <microsim/MSParkingArea.h>
      55              : #include <microsim/MSStop.h>
      56              : #include <microsim/traffic_lights/MSRailSignal.h>
      57              : #include <microsim/traffic_lights/MSRailSignalConstraint.h>
      58              : #include <microsim/transportables/MSPerson.h>
      59              : #include <microsim/devices/MSDevice_Routing.h>
      60              : #include <microsim/devices/MSRoutingEngine.h>
      61              : #include "MSTriggeredRerouter.h"
      62              : 
      63              : #include <mesosim/MELoop.h>
      64              : #include <mesosim/MESegment.h>
      65              : 
      66              : //#define DEBUG_REROUTER
      67              : //#define DEBUG_OVERTAKING
      68              : #define DEBUGCOND(veh) (veh.isSelected())
      69              : //#define DEBUGCOND(veh) (true)
      70              : //#define DEBUGCOND(veh) (veh.getID() == "")
      71              : 
      72              : /// assume that a faster train has more priority and a slower train doesn't matter
      73              : #define DEFAULT_PRIO_OVERTAKER 1
      74              : #define DEFAULT_PRIO_OVERTAKEN 0.001
      75              : 
      76              : // ===========================================================================
      77              : // static member definition
      78              : // ===========================================================================
      79              : MSEdge MSTriggeredRerouter::mySpecialDest_keepDestination("MSTriggeredRerouter_keepDestination", -1, SumoXMLEdgeFunc::UNKNOWN, "", "", "", -1, 0);
      80              : MSEdge MSTriggeredRerouter::mySpecialDest_terminateRoute("MSTriggeredRerouter_terminateRoute", -1, SumoXMLEdgeFunc::UNKNOWN, "", "", "", -1, 0);
      81              : const double MSTriggeredRerouter::DEFAULT_MAXDELAY(7200);
      82              : std::map<std::string, MSTriggeredRerouter*> MSTriggeredRerouter::myInstances;
      83              : 
      84              : 
      85              : // ===========================================================================
      86              : // method definitions
      87              : // ===========================================================================
      88         4707 : MSTriggeredRerouter::MSTriggeredRerouter(const std::string& id,
      89              :         const MSEdgeVector& edges, double prob, bool off, bool optional,
      90         4707 :         SUMOTime timeThreshold, const std::string& vTypes, const Position& pos, const double radius) :
      91              :     Named(id),
      92              :     MSMoveReminder(id),
      93              :     MSStoppingPlaceRerouter("parking"),
      94         4707 :     myEdges(edges),
      95         4707 :     myProbability(prob),
      96         4707 :     myUserProbability(prob),
      97         4707 :     myAmInUserMode(false),
      98         4707 :     myAmOptional(optional),
      99         4707 :     myPosition(pos),
     100         4707 :     myRadius(radius),
     101         4707 :     myTimeThreshold(timeThreshold),
     102         4707 :     myHaveParkProbs(false),
     103        14121 :     myHaveClosingUntil(false)
     104              : {
     105         4707 :     myInstances[id] = this;
     106              :     // build actors
     107        10914 :     for (const MSEdge* const e : edges) {
     108         6207 :         if (MSGlobals::gUseMesoSim) {
     109          819 :             MSGlobals::gMesoNet->getSegmentForEdge(*e)->addDetector(this);
     110              :         }
     111        13144 :         for (MSLane* const lane : e->getLanes()) {
     112         6937 :             lane->addMoveReminder(this);
     113              :         }
     114              :     }
     115         4707 :     if (off) {
     116            1 :         setUserMode(true);
     117            1 :         setUserUsageProbability(0);
     118              :     }
     119         9414 :     const std::vector<std::string> vt = StringTokenizer(vTypes).getVector();
     120              :     myVehicleTypes.insert(vt.begin(), vt.end());
     121              :     if (myPosition == Position::INVALID) {
     122         4222 :         myPosition = edges.front()->getLanes()[0]->getShape()[0];
     123              :     }
     124         4707 : }
     125              : 
     126              : 
     127         8608 : MSTriggeredRerouter::~MSTriggeredRerouter() {
     128              :     myInstances.erase(getID());
     129        13311 : }
     130              : 
     131              : 
     132              : // ------------ loading begin
     133              : void
     134        22995 : MSTriggeredRerouter::myStartElement(int element,
     135              :                                     const SUMOSAXAttributes& attrs) {
     136        22995 :     if (element == SUMO_TAG_INTERVAL) {
     137         4566 :         bool ok = true;
     138         4566 :         myParsedRerouteInterval = RerouteInterval();
     139         4566 :         myParsedRerouteInterval.begin = attrs.getOptSUMOTimeReporting(SUMO_ATTR_BEGIN, nullptr, ok, -1);
     140         4566 :         myParsedRerouteInterval.end = attrs.getOptSUMOTimeReporting(SUMO_ATTR_END, nullptr, ok, SUMOTime_MAX);
     141         4566 :         if (myParsedRerouteInterval.begin >= myParsedRerouteInterval.end) {
     142           18 :             throw ProcessError(TLF("rerouter '%': interval end % is not after begin %.", getID(),
     143              :                                    time2string(myParsedRerouteInterval.end),
     144           18 :                                    time2string(myParsedRerouteInterval.begin)));
     145              :         }
     146              :     }
     147        22989 :     if (element == SUMO_TAG_DEST_PROB_REROUTE) {
     148              :         // by giving probabilities of new destinations
     149              :         // get the destination edge
     150          289 :         std::string dest = attrs.getStringSecure(SUMO_ATTR_ID, "");
     151          289 :         if (dest == "") {
     152            0 :             throw ProcessError(TLF("rerouter '%': destProbReroute has no destination edge id.", getID()));
     153              :         }
     154          289 :         MSEdge* to = MSEdge::dictionary(dest);
     155          289 :         if (to == nullptr) {
     156          126 :             if (dest == "keepDestination") {
     157              :                 to = &mySpecialDest_keepDestination;
     158           94 :             } else if (dest == "terminateRoute") {
     159              :                 to = &mySpecialDest_terminateRoute;
     160              :             } else {
     161            0 :                 throw ProcessError(TLF("rerouter '%': Destination edge '%' is not known.", getID(), dest));
     162              :             }
     163              :         }
     164              :         // get the probability to reroute
     165          289 :         bool ok = true;
     166          289 :         double prob = attrs.getOpt<double>(SUMO_ATTR_PROB, getID().c_str(), ok, 1.);
     167          289 :         if (!ok) {
     168            0 :             throw ProcessError();
     169              :         }
     170          289 :         if (prob < 0) {
     171            0 :             throw ProcessError(TLF("rerouter '%': Attribute 'probability' for destination '%' is negative (must not).", getID(), dest));
     172              :         }
     173              :         // add
     174          289 :         myParsedRerouteInterval.edgeProbs.add(to, prob);
     175              :     }
     176              : 
     177        22989 :     if (element == SUMO_TAG_CLOSING_REROUTE) {
     178              :         // by closing edge
     179         1292 :         const std::string& closed_id = attrs.getStringSecure(SUMO_ATTR_ID, "");
     180         1292 :         MSEdge* const closedEdge = MSEdge::dictionary(closed_id);
     181         1292 :         if (closedEdge == nullptr) {
     182            0 :             throw ProcessError(TLF("rerouter '%': Edge '%' to close is not known.", getID(), closed_id));
     183              :         }
     184              :         bool ok;
     185         1292 :         SVCPermissions permissions = SVC_UNSPECIFIED;
     186         1292 :         if (attrs.hasAttribute(SUMO_ATTR_ALLOW) || attrs.hasAttribute(SUMO_ATTR_DISALLOW)) {
     187          864 :             const std::string allow = attrs.getOpt<std::string>(SUMO_ATTR_ALLOW, getID().c_str(), ok, "", false);
     188          864 :             const std::string disallow = attrs.getOpt<std::string>(SUMO_ATTR_DISALLOW, getID().c_str(), ok, "");
     189          864 :             permissions = parseVehicleClasses(allow, disallow);
     190              :         }
     191         1292 :         const SUMOTime until = attrs.getOptSUMOTimeReporting(SUMO_ATTR_UNTIL, nullptr, ok, TIME2STEPS(-1));
     192         1292 :         myParsedRerouteInterval.closed[closedEdge] = std::make_pair(permissions, STEPS2TIME(until));
     193         1292 :         myHaveClosingUntil |= until > 0;
     194              :     }
     195              : 
     196        22989 :     if (element == SUMO_TAG_CLOSING_LANE_REROUTE) {
     197              :         // by closing lane
     198          197 :         std::string closed_id = attrs.getStringSecure(SUMO_ATTR_ID, "");
     199          197 :         MSLane* closedLane = MSLane::dictionary(closed_id);
     200          197 :         if (closedLane == nullptr) {
     201            0 :             throw ProcessError(TLF("rerouter '%': Lane '%' to close is not known.", getID(), closed_id));
     202              :         }
     203              :         SVCPermissions permissions = SVC_AUTHORITY;
     204          197 :         if (attrs.hasAttribute(SUMO_ATTR_ALLOW) || attrs.hasAttribute(SUMO_ATTR_DISALLOW)) {
     205              :             bool ok;
     206          115 :             const std::string allow = attrs.getOpt<std::string>(SUMO_ATTR_ALLOW, getID().c_str(), ok, "", false);
     207          115 :             const std::string disallow = attrs.getOpt<std::string>(SUMO_ATTR_DISALLOW, getID().c_str(), ok, "");
     208          115 :             permissions = parseVehicleClasses(allow, disallow);
     209              :         }
     210          197 :         myParsedRerouteInterval.closedLanes[closedLane] = permissions;
     211              :     }
     212              : 
     213        22989 :     if (element == SUMO_TAG_ROUTE_PROB_REROUTE) {
     214              :         // by explicit rerouting using routes
     215              :         // check if route exists
     216          791 :         std::string routeStr = attrs.getStringSecure(SUMO_ATTR_ID, "");
     217          791 :         if (routeStr == "") {
     218            0 :             throw ProcessError(TLF("rerouter '%': routeProbReroute has no alternative route id.", getID()));
     219              :         }
     220          791 :         ConstMSRoutePtr route = MSRoute::dictionary(routeStr);
     221          791 :         if (route == nullptr) {
     222            0 :             throw ProcessError(TLF("rerouter '%': Alternative route '%' does not exist.", getID(), routeStr));
     223              :         }
     224              : 
     225              :         // get the probability to reroute
     226          791 :         bool ok = true;
     227          791 :         double prob = attrs.getOpt<double>(SUMO_ATTR_PROB, getID().c_str(), ok, 1.);
     228          791 :         if (!ok) {
     229            0 :             throw ProcessError();
     230              :         }
     231          791 :         if (prob < 0) {
     232            0 :             throw ProcessError(TLF("rerouter '%': Attribute 'probability' for alternative route '%' is negative (must not).", getID(), routeStr));
     233              :         }
     234              :         // add
     235         1582 :         myParsedRerouteInterval.routeProbs.add(route, prob);
     236              :     }
     237              : 
     238        22989 :     if (element == SUMO_TAG_PARKING_AREA_REROUTE) {
     239        15645 :         std::string parkingarea = attrs.getStringSecure(SUMO_ATTR_ID, "");
     240        15645 :         if (parkingarea == "") {
     241            0 :             throw ProcessError(TLF("rerouter '%': parkingAreaReroute requires a parkingArea id.", getID()));
     242              :         }
     243        15645 :         MSParkingArea* pa = static_cast<MSParkingArea*>(MSNet::getInstance()->getStoppingPlace(parkingarea, SUMO_TAG_PARKING_AREA));
     244        15645 :         if (pa == nullptr) {
     245            0 :             throw ProcessError(TLF("rerouter '%': parkingArea '%' is not known.", getID(), parkingarea));
     246              :         }
     247              :         // get the probability to reroute
     248        15645 :         bool ok = true;
     249        15645 :         const double prob = attrs.getOpt<double>(SUMO_ATTR_PROB, getID().c_str(), ok, 1.);
     250        15645 :         if (!ok) {
     251            0 :             throw ProcessError();
     252              :         }
     253        15645 :         if (prob < 0) {
     254            0 :             throw ProcessError(TLF("rerouter '%': Attribute 'probability' for parkingArea '%' is negative (must not).", getID(), parkingarea));
     255              :         }
     256        15645 :         const bool visible = attrs.getOpt<bool>(SUMO_ATTR_VISIBLE, getID().c_str(), ok, false);
     257              :         // add
     258        15645 :         myParsedRerouteInterval.parkProbs.add(std::make_pair(pa, visible), prob);
     259        15645 :         myHaveParkProbs = true;
     260              :     }
     261              : 
     262        22989 :     if (element == SUMO_TAG_VIA_PROB_REROUTE) {
     263              :         // by giving probabilities of vias
     264           66 :         std::string viaID  = attrs.getStringSecure(SUMO_ATTR_ID, "");
     265           66 :         if (viaID == "") {
     266            0 :             throw ProcessError(TLF("rerouter '%': No via edge id given.", getID()));
     267              :         }
     268           66 :         MSEdge* const via = MSEdge::dictionary(viaID);
     269           66 :         if (via == nullptr) {
     270            0 :             throw ProcessError(TLF("rerouter '%': Via Edge '%' is not known.", getID(), viaID));
     271              :         }
     272              :         // get the probability to reroute
     273           66 :         bool ok = true;
     274           66 :         double prob = attrs.getOpt<double>(SUMO_ATTR_PROB, getID().c_str(), ok, 1.);
     275           66 :         if (!ok) {
     276            0 :             throw ProcessError();
     277              :         }
     278           66 :         if (prob < 0) {
     279            0 :             throw ProcessError(TLF("rerouter '%': Attribute 'probability' for via '%' is negative (must not).", getID(), viaID));
     280              :         }
     281              :         // add
     282           66 :         myParsedRerouteInterval.edgeProbs.add(via, prob);
     283           66 :         myParsedRerouteInterval.isVia = true;
     284              :     }
     285        22989 :     if (element == SUMO_TAG_OVERTAKING_REROUTE) {
     286              :         // for letting a slow train use a siding to be overtaken by a fast train
     287              :         OvertakeLocation oloc;
     288           99 :         bool ok = true;
     289          396 :         for (const std::string& edgeID : attrs.get<std::vector<std::string> >(SUMO_ATTR_MAIN, getID().c_str(), ok)) {
     290          297 :             MSEdge* edge = MSEdge::dictionary(edgeID);
     291          297 :             if (edge == nullptr) {
     292            0 :                 throw InvalidArgument(TLF("The main edge '%' to use within rerouter '%' is not known.", edgeID, getID()));
     293              :             }
     294          297 :             oloc.main.push_back(edge);
     295          297 :             oloc.cMain.push_back(edge);
     296           99 :         }
     297          396 :         for (const std::string& edgeID : attrs.get<std::vector<std::string> >(SUMO_ATTR_SIDING, getID().c_str(), ok)) {
     298          297 :             MSEdge* edge = MSEdge::dictionary(edgeID);
     299          297 :             if (edge == nullptr) {
     300            0 :                 throw InvalidArgument(TLF("The siding edge '%' to use within rerouter '%' is not known.", edgeID, getID()));
     301              :             }
     302          297 :             oloc.siding.push_back(edge);
     303          297 :             oloc.cSiding.push_back(edge);
     304           99 :         }
     305           99 :         oloc.sidingExit = findSignal(oloc.cSiding.begin(), oloc.cSiding.end());
     306           99 :         if (oloc.sidingExit == nullptr) {
     307            0 :             throw InvalidArgument(TLF("The siding within rerouter '%' does not have a rail signal.", getID()));
     308              :         }
     309          198 :         for (auto it = oloc.cSiding.begin(); it != oloc.cSiding.end(); it++) {
     310          198 :             oloc.sidingLength += (*it)->getLength();
     311          198 :             if ((*it)->getToJunction()->getID() == oloc.sidingExit->getID()) {
     312              :                 break;
     313              :             }
     314              :         }
     315           99 :         oloc.minSaving = attrs.getOpt<double>(SUMO_ATTR_MINSAVING, getID().c_str(), ok, 300);
     316           99 :         const bool hasAlternatives = myParsedRerouteInterval.overtakeLocations.size() > 0;
     317           99 :         oloc.defer = attrs.getOpt<bool>(SUMO_ATTR_DEFER, getID().c_str(), ok, hasAlternatives);
     318           99 :         myParsedRerouteInterval.overtakeLocations.push_back(oloc);
     319           99 :     }
     320        22989 :     if (element == SUMO_TAG_STATION_REROUTE) {
     321              :         // for letting a train switch it's stopping place in case of conflict
     322           45 :         const std::string stopID = attrs.getStringSecure(SUMO_ATTR_ID, "");
     323           45 :         if (stopID == "") {
     324            0 :             throw ProcessError(TLF("rerouter '%': stationReroute requires a stopping place id.", getID()));
     325              :         }
     326           45 :         MSStoppingPlace* stop = MSNet::getInstance()->getStoppingPlace(stopID);
     327           45 :         if (stop == nullptr) {
     328            0 :             throw ProcessError(TLF("rerouter '%': stopping place '%' is not known.", getID(), stopID));
     329              :         }
     330           45 :         myParsedRerouteInterval.stopAlternatives.push_back(std::make_pair(stop, true));
     331              :     }
     332        22989 : }
     333              : 
     334              : 
     335              : void
     336        27690 : MSTriggeredRerouter::myEndElement(int element) {
     337        27690 :     if (element == SUMO_TAG_INTERVAL) {
     338              :         // precompute permissionsAllowAll
     339              :         bool allowAll = true;
     340         4984 :         for (const auto& entry : myParsedRerouteInterval.closed) {
     341         1078 :             allowAll = allowAll && entry.second.first == SVC_UNSPECIFIED;
     342              :             if (!allowAll) {
     343              :                 break;
     344              :             }
     345              :         }
     346         4560 :         myParsedRerouteInterval.permissionsAllowAll = allowAll;
     347              : 
     348        20202 :         for (auto paVi : myParsedRerouteInterval.parkProbs.getVals()) {
     349        15642 :             dynamic_cast<MSParkingArea*>(paVi.first)->setNumAlternatives((int)myParsedRerouteInterval.parkProbs.getVals().size() - 1);
     350              :         }
     351         4560 :         if (myParsedRerouteInterval.closedLanes.size() > 0) {
     352              :             // collect edges that are affect by a closed lane
     353              :             std::set<MSEdge*> affected;
     354          332 :             for (std::pair<MSLane*, SVCPermissions> settings : myParsedRerouteInterval.closedLanes) {
     355          191 :                 affected.insert(&settings.first->getEdge());
     356              :             }
     357          141 :             myParsedRerouteInterval.closedLanesAffected.insert(myParsedRerouteInterval.closedLanesAffected.begin(), affected.begin(), affected.end());
     358              :         }
     359         4560 :         const SUMOTime closingBegin = myParsedRerouteInterval.begin;
     360         4560 :         const SUMOTime simBegin = string2time(OptionsCont::getOptions().getString("begin"));
     361         4560 :         if (closingBegin < simBegin && myParsedRerouteInterval.end > simBegin) {
     362              :             // interval started before simulation begin but is still active at
     363              :             // the start of the simulation
     364          445 :             myParsedRerouteInterval.begin = simBegin;
     365              :         }
     366         4560 :         myIntervals.push_back(myParsedRerouteInterval);
     367         4560 :         myIntervals.back().id = (long long int)&myIntervals.back();
     368         4560 :         if (!(myParsedRerouteInterval.closed.empty() && myParsedRerouteInterval.closedLanes.empty())) {
     369         2310 :             MSNet::getInstance()->getBeginOfTimestepEvents()->addEvent(
     370         1155 :                 new WrappingCommand<MSTriggeredRerouter>(this, &MSTriggeredRerouter::setPermissions), myParsedRerouteInterval.begin);
     371              :         }
     372              :     }
     373        27690 : }
     374              : 
     375              : 
     376              : // ------------ loading end
     377              : 
     378              : 
     379              : SUMOTime
     380         1337 : MSTriggeredRerouter::setPermissions(const SUMOTime currentTime) {
     381              :     bool updateVehicles = false;
     382         2723 :     for (const RerouteInterval& i : myIntervals) {
     383         1386 :         if (i.begin == currentTime && !(i.closed.empty() && i.closedLanes.empty()) /*&& i.permissions != SVCAll*/) {
     384         2394 :             for (const auto& settings : i.closed) {
     385         1254 :                 if (settings.second.first != SVC_UNSPECIFIED) {
     386         1718 :                     for (MSLane* lane : settings.first->getLanes()) {
     387              :                         //std::cout << SIMTIME << " closing: intervalID=" << i.id << " lane=" << lane->getID() << " prevPerm=" << getVehicleClassNames(lane->getPermissions()) << " new=" << getVehicleClassNames(settings.second.first) << "\n";
     388          864 :                         lane->setPermissions(settings.second.first, i.id);
     389              :                     }
     390          854 :                     settings.first->rebuildAllowedLanes();
     391              :                     updateVehicles = true;
     392              :                 }
     393              :             }
     394         1347 :             for (std::pair<MSLane*, SVCPermissions> settings : i.closedLanes) {
     395          207 :                 settings.first->setPermissions(settings.second, i.id);
     396          207 :                 settings.first->getEdge().rebuildAllowedLanes();
     397              :                 updateVehicles = true;
     398              :             }
     399         2280 :             MSNet::getInstance()->getBeginOfTimestepEvents()->addEvent(
     400         1140 :                 new WrappingCommand<MSTriggeredRerouter>(this, &MSTriggeredRerouter::setPermissions), i.end);
     401              :         }
     402         1386 :         if (i.end == currentTime && !(i.closed.empty() && i.closedLanes.empty()) /*&& i.permissions != SVCAll*/) {
     403          451 :             for (auto settings : i.closed) {
     404          222 :                 if (settings.second.first != SVC_UNSPECIFIED) {
     405          394 :                     for (MSLane* lane : settings.first->getLanes()) {
     406          197 :                         lane->resetPermissions(i.id);
     407              :                         //std::cout << SIMTIME << " opening: intervalID=" << i.id << " lane=" << lane->getID() << " restore prevPerm=" << getVehicleClassNames(lane->getPermissions()) << "\n";
     408              :                     }
     409          197 :                     settings.first->rebuildAllowedLanes();
     410              :                     updateVehicles = true;
     411              :                 }
     412              :             }
     413          357 :             for (std::pair<MSLane*, SVCPermissions> settings : i.closedLanes) {
     414          128 :                 settings.first->resetPermissions(i.id);
     415          128 :                 settings.first->getEdge().rebuildAllowedLanes();
     416              :                 updateVehicles = true;
     417              :             }
     418              :         }
     419              :     }
     420         1337 :     if (updateVehicles) {
     421          976 :         MSNet::getInstance()->setPermissionsFound();
     422              :         // only vehicles on the affected lanes had their bestlanes updated so far
     423         1958 :         for (MSEdge* e : myEdges) {
     424              :             // also updates vehicles
     425          982 :             e->rebuildAllowedTargets();
     426              :         }
     427              :     }
     428         1337 :     return 0;
     429              : }
     430              : 
     431              : 
     432              : const MSTriggeredRerouter::RerouteInterval*
     433      1193577 : MSTriggeredRerouter::getCurrentReroute(SUMOTime time, SUMOTrafficObject& obj) const {
     434      1725053 :     for (const RerouteInterval& ri : myIntervals) {
     435      1210435 :         if (ri.begin <= time && ri.end > time) {
     436              :             if (
     437              :                 // destProbReroute
     438       701780 :                 ri.edgeProbs.getOverallProb() > 0 ||
     439              :                 // routeProbReroute
     440       158297 :                 ri.routeProbs.getOverallProb() > 0 ||
     441              :                 // parkingZoneReroute
     442       746012 :                 ri.parkProbs.getOverallProb() > 0 ||
     443              :                 // stationReroute
     444              :                 ri.stopAlternatives.size() > 0) {
     445       665313 :                 return &ri;
     446              :             }
     447        40342 :             if (!ri.closed.empty() || !ri.closedLanesAffected.empty() || !ri.overtakeLocations.empty()) {
     448        40342 :                 const std::set<SUMOTrafficObject::NumericalID>& edgeIndices = obj.getUpcomingEdgeIDs();
     449        80684 :                 if (affected(edgeIndices, ri.getClosedEdges())
     450        40342 :                         || affected(edgeIndices, ri.closedLanesAffected)) {
     451        13502 :                     return &ri;
     452              :                 }
     453        26840 :                 for (const OvertakeLocation& oloc : ri.overtakeLocations) {
     454          144 :                     if (affected(edgeIndices, oloc.main)) {
     455              :                         return &ri;
     456              :                     }
     457              :                 }
     458              : 
     459              :             }
     460              :         }
     461              :     }
     462              :     return nullptr;
     463              : }
     464              : 
     465              : 
     466              : const MSTriggeredRerouter::RerouteInterval*
     467       318748 : MSTriggeredRerouter::getCurrentReroute(SUMOTime time) const {
     468       318764 :     for (const RerouteInterval& ri : myIntervals) {
     469       318748 :         if (ri.begin <= time && ri.end > time) {
     470       318732 :             if (ri.edgeProbs.getOverallProb() != 0 || ri.routeProbs.getOverallProb() != 0 || ri.parkProbs.getOverallProb() != 0
     471       318992 :                     || !ri.closed.empty() || !ri.closedLanesAffected.empty() || !ri.overtakeLocations.empty()) {
     472              :                 return &ri;
     473              :             }
     474              :         }
     475              :     }
     476              :     return nullptr;
     477              : }
     478              : 
     479              : 
     480              : bool
     481       689683 : MSTriggeredRerouter::notifyEnter(SUMOTrafficObject& tObject, MSMoveReminder::Notification reason, const MSLane* /* enteredLane */) {
     482       689683 :     if (myAmOptional || myRadius != std::numeric_limits<double>::max()) {
     483              :         return true;
     484              :     }
     485       689523 :     return triggerRouting(tObject, reason);
     486              : }
     487              : 
     488              : 
     489              : bool
     490       503488 : MSTriggeredRerouter::notifyMove(SUMOTrafficObject& veh, double /*oldPos*/,
     491              :                                 double /*newPos*/, double /*newSpeed*/) {
     492       503488 :     return triggerRouting(veh, NOTIFICATION_JUNCTION);
     493              : }
     494              : 
     495              : 
     496              : bool
     497        17888 : MSTriggeredRerouter::notifyLeave(SUMOTrafficObject& /*veh*/, double /*lastPos*/,
     498              :                                  MSMoveReminder::Notification reason, const MSLane* /* enteredLane */) {
     499        17888 :     return reason == NOTIFICATION_LANE_CHANGE;
     500              : }
     501              : 
     502              : 
     503              : bool
     504      1193681 : MSTriggeredRerouter::triggerRouting(SUMOTrafficObject& tObject, MSMoveReminder::Notification reason) {
     505      1193681 :     if (!applies(tObject)) {
     506              :         return false;
     507              :     }
     508      1193577 :     if (myRadius != std::numeric_limits<double>::max() && tObject.getPosition().distanceTo(myPosition) > myRadius) {
     509            0 :         return true;
     510              :     }
     511              :     // check whether the vehicle shall be rerouted
     512      1193577 :     const SUMOTime now = MSNet::getInstance()->getCurrentTimeStep();
     513      1193577 :     const MSTriggeredRerouter::RerouteInterval* const rerouteDef = getCurrentReroute(now, tObject);
     514      1193577 :     if (rerouteDef == nullptr) {
     515              :         return true; // an active interval could appear later
     516              :     }
     517       678959 :     const double prob = myAmInUserMode ? myUserProbability : myProbability;
     518       678959 :     if (prob < 1 && RandHelper::rand(tObject.getRNG()) > prob) {
     519              :         return false; // XXX another interval could appear later but we would have to track whether the current interval was already tried
     520              :     }
     521       678630 :     if (myTimeThreshold > 0 && MAX2(tObject.getWaitingTime(), tObject.getWaitingTime(true)) < myTimeThreshold) {
     522              :         return true; // waiting time may be reached later
     523              :     }
     524       670906 :     if (reason == NOTIFICATION_LANE_CHANGE) {
     525              :         return false;
     526              :     }
     527              :     // if we have a closingLaneReroute it may still affect the network topology (i.e. by closing a turning lane).
     528              :     // Even if the topology stays unchanged, vehicles with a rerouting device could reroute around jams that form due to capacity reduction
     529       653197 :     const bool hasReroutingDevice = tObject.getDevice(typeid(MSDevice_Routing)) != nullptr;
     530       653197 :     const MSEdge* lastEdge = tObject.getRerouteDestination();
     531              : #ifdef DEBUG_REROUTER
     532              :     if (DEBUGCOND(tObject)) {
     533              :         std::cout << SIMTIME << " veh=" << tObject.getID() << " check rerouter " << getID() << " lane=" << Named::getIDSecure(tObject.getLane()) << " edge=" << tObject.getEdge()->getID() << " finalEdge=" << lastEdge->getID() /*<< " arrivalPos=" << tObject.getArrivalPos()*/ << "\n";
     534              :     }
     535              : #endif
     536              : 
     537       653197 :     if (rerouteDef->parkProbs.getOverallProb() > 0) {
     538              : #ifdef HAVE_FOX
     539       111518 :         ScopedLocker<> lock(myNotificationMutex, MSGlobals::gNumSimThreads > 1);
     540              : #endif
     541       111518 :         if (!tObject.isVehicle()) {
     542              :             return false;
     543              :         }
     544              :         SUMOVehicle& veh = static_cast<SUMOVehicle&>(tObject);
     545       111440 :         bool newDestination = false;
     546              :         ConstMSEdgeVector newRoute;
     547       111440 :         MSParkingArea* oldParkingArea = veh.getNextParkingArea();
     548       111440 :         MSParkingArea* newParkingArea = rerouteParkingArea(rerouteDef, veh, newDestination, newRoute);
     549       111440 :         if (newParkingArea != nullptr) {
     550              :             // adapt plans of any riders
     551        34472 :             for (MSTransportable* p : veh.getPersons()) {
     552           48 :                 p->rerouteParkingArea(oldParkingArea, newParkingArea);
     553              :             }
     554              : 
     555        34424 :             if (newDestination && veh.getParameter().arrivalPosProcedure != ArrivalPosDefinition::DEFAULT) {
     556              :                 // update arrival parameters
     557           60 :                 SUMOVehicleParameter* newParameter = new SUMOVehicleParameter();
     558           60 :                 *newParameter = veh.getParameter();
     559           60 :                 newParameter->arrivalPosProcedure = ArrivalPosDefinition::GIVEN;
     560           60 :                 newParameter->arrivalPos = newParkingArea->getEndLanePosition();
     561           60 :                 veh.replaceParameter(newParameter);
     562              :             }
     563              : 
     564              :             SUMOAbstractRouter<MSEdge, SUMOVehicle>& router = hasReroutingDevice
     565        15143 :                     ? MSRoutingEngine::getRouterTT(veh.getRNGIndex(), veh.getVClass(), rerouteDef->getClosed())
     566        68848 :                     : MSNet::getInstance()->getRouterTT(veh.getRNGIndex(), rerouteDef->getClosed());
     567        34424 :             const double routeCost = router.recomputeCosts(newRoute, &veh, MSNet::getInstance()->getCurrentTimeStep());
     568        34424 :             ConstMSEdgeVector prevEdges(veh.getCurrentRouteEdge(), veh.getRoute().end());
     569        34424 :             resetClosedEdges(hasReroutingDevice, veh);
     570        34424 :             const double previousCost = router.recomputeCosts(prevEdges, &veh, MSNet::getInstance()->getCurrentTimeStep());
     571        34424 :             const double savings = previousCost - routeCost;
     572              :             //if (getID() == "ego") std::cout << SIMTIME << " pCost=" << previousCost << " cost=" << routeCost
     573              :             //        << " prevEdges=" << toString(prevEdges)
     574              :             //        << " newEdges=" << toString(edges)
     575              :             //        << "\n";
     576              : 
     577              :             std::string errorMsg;
     578        34424 :             if (veh.replaceParkingArea(newParkingArea, errorMsg)) {
     579        68848 :                 veh.replaceRouteEdges(newRoute, routeCost, savings, getID() + ":" + toString(SUMO_TAG_PARKING_AREA_REROUTE), false, false, false);
     580        34424 :                 if (oldParkingArea->isReservable()) {
     581           18 :                     oldParkingArea->removeSpaceReservation(&veh);
     582              :                 }
     583        34424 :                 if (newParkingArea->isReservable()) {
     584           18 :                     newParkingArea->addSpaceReservation(&veh);
     585              :                 }
     586              :             } else {
     587            0 :                 WRITE_WARNING("Vehicle '" + veh.getID() + "' at rerouter '" + getID()
     588              :                               + "' could not reroute to new parkingArea '" + newParkingArea->getID()
     589              :                               + "' reason=" + errorMsg + ", time=" + time2string(MSNet::getInstance()->getCurrentTimeStep()) + ".");
     590              :             }
     591        34424 :         } else {
     592        77016 :             if (oldParkingArea && oldParkingArea->isReservable()) {
     593           18 :                 oldParkingArea->addSpaceReservation(&veh);
     594              :             }
     595              :         }
     596              :         return false;
     597       111440 :     }
     598       541679 :     if (rerouteDef->overtakeLocations.size() > 0) {
     599          144 :         if (!tObject.isVehicle()) {
     600              :             return false;
     601              :         }
     602              :         SUMOVehicle& veh = static_cast<SUMOVehicle&>(tObject);
     603          144 :         const ConstMSEdgeVector& oldEdges = veh.getRoute().getEdges();
     604              :         double bestSavings = -std::numeric_limits<double>::max();
     605              :         double netSaving;
     606              :         int bestIndex = -1;
     607              :         MSRouteIterator bestMainStart = oldEdges.end();
     608              :         std::pair<const SUMOVehicle*, MSRailSignal*> best_overtaker_signal(nullptr, nullptr);
     609              :         int index = -1;
     610              :         // sort locations by descending distance to vehicle
     611              :         std::vector<std::pair<int, int> > sortedLocs;
     612          330 :         for (const OvertakeLocation& oloc : rerouteDef->overtakeLocations) {
     613          186 :             index++;
     614          186 :             if (veh.getLength() > oloc.sidingLength) {
     615            3 :                 continue;
     616              :             }
     617          183 :             auto mainStart = std::find(veh.getCurrentRouteEdge(), oldEdges.end(), oloc.main.front());
     618          183 :             if (mainStart == oldEdges.end()
     619              :                     // exit main within
     620          366 :                     || ConstMSEdgeVector(mainStart, mainStart + oloc.main.size()) != oloc.cMain
     621              :                     // stop in main
     622          366 :                     || (veh.hasStops() && veh.getNextStop().edge < (mainStart + oloc.main.size()))) {
     623              :                 //std::cout << SIMTIME << " veh=" << veh.getID() << " wrong route or stop\n";
     624            0 :                 continue;
     625              :             }
     626              :             // negated iterator distance for descending order
     627          183 :             sortedLocs.push_back(std::make_pair(-(int)(mainStart - veh.getCurrentRouteEdge()), index));
     628              :         }
     629          144 :         std::sort(sortedLocs.begin(), sortedLocs.end());
     630          327 :         for (const auto& item : sortedLocs) {
     631          183 :             index = item.second;
     632          183 :             const OvertakeLocation& oloc = rerouteDef->overtakeLocations[index];
     633          183 :             auto mainStart = veh.getCurrentRouteEdge() - item.first;  // subtracting negative difference
     634          183 :             std::pair<const SUMOVehicle*, MSRailSignal*> overtaker_signal = overtakingTrain(veh, mainStart, oloc, netSaving);
     635          183 :             if (overtaker_signal.first != nullptr && netSaving > bestSavings) {
     636              :                 bestSavings = netSaving;
     637              :                 bestIndex = index;
     638              :                 best_overtaker_signal = overtaker_signal;
     639              :                 bestMainStart = mainStart;
     640              : #ifdef DEBUG_OVERTAKING
     641              :                 std::cout << "    newBest index=" << bestIndex << " saving=" << bestSavings << "\n";
     642              : #endif
     643              :             }
     644              :         }
     645          144 :         if (bestIndex >= 0) {
     646           41 :             const OvertakeLocation& oloc = rerouteDef->overtakeLocations[bestIndex];
     647           41 :             if (oloc.defer) {
     648            5 :                 return false;
     649              :             }
     650              :             SUMOAbstractRouter<MSEdge, SUMOVehicle>& router = hasReroutingDevice
     651            0 :                     ? MSRoutingEngine::getRouterTT(veh.getRNGIndex(), veh.getVClass(), rerouteDef->getClosed())
     652           72 :                     : MSNet::getInstance()->getRouterTT(veh.getRNGIndex(), rerouteDef->getClosed());
     653           36 :             ConstMSEdgeVector newEdges(veh.getCurrentRouteEdge(), bestMainStart);
     654           36 :             newEdges.insert(newEdges.end(), oloc.siding.begin(), oloc.siding.end());
     655           36 :             newEdges.insert(newEdges.end(), bestMainStart + oloc.main.size(), oldEdges.end());
     656           36 :             const double routeCost = router.recomputeCosts(newEdges, &veh, MSNet::getInstance()->getCurrentTimeStep());
     657           36 :             const double savings = (router.recomputeCosts(oloc.cMain, &veh, MSNet::getInstance()->getCurrentTimeStep())
     658           36 :                                     - router.recomputeCosts(oloc.cSiding, &veh, MSNet::getInstance()->getCurrentTimeStep()));
     659           72 :             const std::string info = getID() + ":" + toString(SUMO_TAG_OVERTAKING_REROUTE) + ":" + best_overtaker_signal.first->getID();
     660           36 :             veh.replaceRouteEdges(newEdges, routeCost, savings, info, false, false, false);
     661           36 :             oloc.sidingExit->addConstraint(veh.getID(), new MSRailSignalConstraint_Predecessor(
     662           36 :                                                MSRailSignalConstraint::PREDECESSOR, best_overtaker_signal.second, best_overtaker_signal.first->getID(), 100, true));
     663           36 :             resetClosedEdges(hasReroutingDevice, veh);
     664           36 :         }
     665          139 :         return false;
     666          144 :     }
     667       541535 :     if (rerouteDef->stopAlternatives.size() > 0) {
     668              :         // somewhat similar to parkProbs but taking into account public transport schedule
     669           15 :         if (!tObject.isVehicle()) {
     670              :             return false;
     671              :         }
     672           15 :         checkStopSwitch(static_cast<MSBaseVehicle&>(tObject), rerouteDef);
     673              :     }
     674              :     // get rerouting params
     675       541535 :     ConstMSRoutePtr newRoute = rerouteDef->routeProbs.getOverallProb() > 0 ? rerouteDef->routeProbs.get() : nullptr;
     676              :     // we will use the route if given rather than calling our own dijsktra...
     677       541535 :     if (newRoute != nullptr) {
     678              : #ifdef DEBUG_REROUTER
     679              :         if (DEBUGCOND(tObject)) {
     680              :             std::cout << "    replacedRoute from routeDist " << newRoute->getID() << "\n";
     681              :         }
     682              : #endif
     683       531440 :         tObject.replaceRoute(newRoute, getID());
     684       531440 :         return false; // XXX another interval could appear later but we would have to track whether the currenty interval was already used
     685              :     }
     686              :     const MSEdge* newEdge = lastEdge;
     687              :     // ok, try using a new destination
     688              :     double newArrivalPos = -1;
     689        10095 :     const MSEdgeVector closed = rerouteDef->getClosedEdges();
     690        10095 :     const bool destUnreachable = std::find(closed.begin(), closed.end(), lastEdge) != closed.end();
     691              :     bool keepDestination = false;
     692              :     // if we have a closingReroute, only assign new destinations to vehicles which cannot reach their original destination
     693              :     // if we have a closingLaneReroute, no new destinations should be assigned
     694        10235 :     if (closed.empty() || destUnreachable || (rerouteDef->isVia && affected(tObject.getUpcomingEdgeIDs(), closed))) {
     695         7944 :         newEdge = rerouteDef->edgeProbs.getOverallProb() > 0 ? rerouteDef->edgeProbs.get() : lastEdge;
     696              :         assert(newEdge != nullptr);
     697         7944 :         if (newEdge == &mySpecialDest_terminateRoute) {
     698              :             keepDestination = true;
     699           62 :             newEdge = tObject.getEdge();
     700           62 :             newArrivalPos = tObject.getPositionOnLane(); // instant arrival
     701         7882 :         } else if (newEdge == &mySpecialDest_keepDestination || newEdge == lastEdge) {
     702         4948 :             if (destUnreachable && rerouteDef->permissionsAllowAll) {
     703              :                 // if permissions aren't set vehicles will simply drive through
     704              :                 // the closing unless terminated. If the permissions are specified, assume that the user wants
     705              :                 // vehicles to stand and wait until the closing ends
     706           72 :                 WRITE_WARNINGF(TL("Cannot keep destination edge '%' for vehicle '%' due to closed edges. Terminating route."), lastEdge->getID(), tObject.getID());
     707           24 :                 newEdge = tObject.getEdge();
     708              :             } else {
     709              :                 newEdge = lastEdge;
     710              :             }
     711              :         }
     712              :     }
     713              :     ConstMSEdgeVector edges;
     714              :     std::vector<MSTransportableRouter::TripItem> items;
     715              :     // we have a new destination, let's replace the route (if it is affected)
     716        10095 :     Prohibitions prohibited = rerouteDef->getClosed();
     717        12316 :     if (rerouteDef->closed.empty() || destUnreachable || affected(tObject.getUpcomingEdgeIDs(), closed)) {
     718         9937 :         if (tObject.ignoreTransientPermissions()) {
     719              :             // after learning about network changes, the driver must no longer forget them
     720          245 :             if (!myHaveClosingUntil) {
     721          230 :                 tObject.setRoutingMode(tObject.getRoutingMode() & ~libsumo::ROUTING_MODE_IGNORE_TRANSIENT_PERMISSIONS);
     722           15 :             } else if (hasReroutingDevice && dynamic_cast<MSDevice_Routing*>(tObject.getDevice(typeid(MSDevice_Routing)))->getPeriod() > 0) {
     723           18 :                 WRITE_WARNINGF(TL("Periodic rerouting and rerouting mode 8 for vehicle '%' are incompatible with closingReroute attribute 'until' in rerouter (vehicle may return to an invalid route."),
     724              :                         tObject.getID(), getID());
     725              :             }
     726              :         }
     727         9937 :         if (tObject.isVehicle()) {
     728              :             SUMOVehicle& veh = static_cast<SUMOVehicle&>(tObject);
     729         8249 :             ConstMSEdgeVector prevEdges = veh.getRoute().getEdges();
     730         8249 :             const bool canChangeDest = rerouteDef->edgeProbs.getOverallProb() > 0;
     731              :             MSVehicleRouter& router = hasReroutingDevice
     732         8249 :                                       ? MSRoutingEngine::getRouterTT(veh.getRNGIndex(), veh.getVClass(), prohibited)
     733         5331 :                                       : MSNet::getInstance()->getRouterTT(veh.getRNGIndex(), prohibited);
     734              :             bool ok = false;
     735              :             try {
     736         8249 :                 ok = veh.reroute(now, getID(), router, false, false, canChangeDest, newEdge);
     737           19 :             } catch (ProcessError&) {}
     738         8249 :             if (!ok && !keepDestination && canChangeDest) {
     739              :                 // destination unreachable due to closed intermediate edges. pick among alternative targets
     740          110 :                 RandomDistributor<MSEdge*> edgeProbs2 = rerouteDef->edgeProbs;
     741          110 :                 edgeProbs2.remove(const_cast<MSEdge*>(newEdge));
     742          206 :                 while (!ok && edgeProbs2.getVals().size() > 0) {
     743          142 :                     newEdge = edgeProbs2.get();
     744          142 :                     edgeProbs2.remove(const_cast<MSEdge*>(newEdge));
     745          142 :                     if (newEdge == &mySpecialDest_terminateRoute) {
     746           64 :                         newEdge = veh.getEdge();
     747           64 :                         newArrivalPos = veh.getPositionOnLane(); // instant arrival
     748           80 :                         while (veh.hasStops()) {
     749           16 :                             veh.abortNextStop();
     750              :                         }
     751              :                     }
     752          142 :                     if (newEdge == &mySpecialDest_keepDestination && !rerouteDef->permissionsAllowAll) {
     753              :                         newEdge = lastEdge;
     754              :                         break;
     755              :                     }
     756              :                     try {
     757           96 :                         ok = veh.reroute(now, getID(), router, false, false, true, newEdge);
     758            0 :                     } catch (ProcessError&) {}
     759              :                 }
     760              :             }
     761         8249 :             resetClosedEdges(hasReroutingDevice, tObject);
     762         8249 :             if (ok) {
     763              :                 // since the old route was closed, savings would be infinite. This isn't useful
     764         7749 :                 const double previousCost = router.recomputeCosts(prevEdges, &veh, MSNet::getInstance()->getCurrentTimeStep());
     765         7749 :                 const double savings = previousCost - veh.getRoute().getCosts();
     766         7749 :                 const_cast<MSRoute&>(veh.getRoute()).setSavings(savings);
     767              :             }
     768         8249 :             if (!rerouteDef->isVia) {
     769              : #ifdef DEBUG_REROUTER
     770              :                 if (DEBUGCOND(tObject)) std::cout << "   rerouting:  newDest=" << newEdge->getID()
     771              :                                                       << " newEdges=" << toString(edges)
     772              :                                                       << " newArrivalPos=" << newArrivalPos << " numClosed=" << rerouteDef->closed.size()
     773              :                                                       << " destUnreachable=" << destUnreachable << " containsClosed=" << veh.getRoute().containsAnyOf(closed) << "\n";
     774              : #endif
     775         8109 :                 if (ok && newArrivalPos != -1) {
     776              :                     // must be called here because replaceRouteEdges may also set the arrivalPos
     777          114 :                     veh.setArrivalPos(newArrivalPos);
     778              :                 }
     779              : 
     780              :             }
     781         8249 :         } else {
     782              :             // person rerouting here
     783              :             MSTransportableRouter& router = hasReroutingDevice
     784         1688 :                                             ? MSRoutingEngine::getIntermodalRouterTT(tObject.getRNGIndex(), prohibited)
     785         1688 :                                             : MSNet::getInstance()->getIntermodalRouter(tObject.getRNGIndex(), 0, prohibited);
     786         5064 :             const bool success = router.compute(tObject.getEdge(), newEdge, tObject.getPositionOnLane(), "",
     787         1688 :                                                 rerouteDef->isVia ? newEdge->getLength() / 2. : tObject.getParameter().arrivalPos, "",
     788         1688 :                                                 tObject.getMaxSpeed(), nullptr, tObject.getVTypeParameter(), 0, now, items);
     789         1688 :             if (!rerouteDef->isVia) {
     790          808 :                 if (success) {
     791         1616 :                     for (const MSTransportableRouter::TripItem& it : items) {
     792          808 :                         if (!it.edges.empty() && !edges.empty() && edges.back() == it.edges.front()) {
     793              :                             edges.pop_back();
     794              :                         }
     795          808 :                         edges.insert(edges.end(), std::make_move_iterator(it.edges.begin()), std::make_move_iterator(it.edges.end()));
     796          808 :                         if (!edges.empty()) {
     797          808 :                             static_cast<MSPerson&>(tObject).replaceWalk(edges, tObject.getPositionOnLane(), 0, 1);
     798              :                         }
     799              :                     }
     800              :                 } else {
     801              :                     // maybe the pedestrian model still finds a way (JuPedSim)
     802            0 :                     static_cast<MSPerson&>(tObject).replaceWalk({tObject.getEdge(), newEdge}, tObject.getPositionOnLane(), 0, 1);
     803              :                 }
     804              :             }
     805              :         }
     806         9937 :         if (!prohibited.empty()) {
     807         2160 :             resetClosedEdges(hasReroutingDevice, tObject);
     808              :         }
     809              :     }
     810              :     // it was only a via so calculate the remaining part
     811        10095 :     if (rerouteDef->isVia && newEdge != lastEdge) {
     812         1020 :         if (tObject.isVehicle()) {
     813              :             SUMOVehicle& veh = static_cast<SUMOVehicle&>(tObject);
     814          140 :             if (!edges.empty()) {
     815              :                 edges.pop_back();
     816              :             }
     817              :             MSVehicleRouter& router = hasReroutingDevice
     818          140 :                                       ? MSRoutingEngine::getRouterTT(veh.getRNGIndex(), veh.getVClass(), prohibited)
     819          140 :                                       : MSNet::getInstance()->getRouterTT(veh.getRNGIndex(), prohibited);
     820          140 :             router.compute(newEdge, lastEdge, &veh, now, edges);
     821          140 :             const double routeCost = router.recomputeCosts(edges, &veh, now);
     822              :             hasReroutingDevice
     823          140 :             ? MSRoutingEngine::getRouterTT(veh.getRNGIndex(), veh.getVClass())
     824          280 :             : MSNet::getInstance()->getRouterTT(veh.getRNGIndex()); // reset closed edges
     825          140 :             const bool useNewRoute = veh.replaceRouteEdges(edges, routeCost, 0, getID());
     826              : #ifdef DEBUG_REROUTER
     827              :             if (DEBUGCOND(tObject)) std::cout << "   rerouting:  newDest=" << newEdge->getID()
     828              :                                                   << " newEdges=" << toString(edges)
     829              :                                                   << " useNewRoute=" << useNewRoute << " newArrivalPos=" << newArrivalPos << " numClosed=" << rerouteDef->closed.size()
     830              :                                                   << " destUnreachable=" << destUnreachable << " containsClosed=" << veh.getRoute().containsAnyOf(closed) << "\n";
     831              : #endif
     832          140 :             if (useNewRoute && newArrivalPos != -1) {
     833              :                 // must be called here because replaceRouteEdges may also set the arrivalPos
     834            0 :                 veh.setArrivalPos(newArrivalPos);
     835              :             }
     836              :         } else {
     837              :             // person rerouting here
     838          880 :             bool success = !items.empty();
     839          880 :             if (success) {
     840              :                 MSTransportableRouter& router = hasReroutingDevice
     841          880 :                                                 ? MSRoutingEngine::getIntermodalRouterTT(tObject.getRNGIndex(), prohibited)
     842          880 :                                                 : MSNet::getInstance()->getIntermodalRouter(tObject.getRNGIndex(), 0, prohibited);
     843         2640 :                 success = router.compute(newEdge, lastEdge, newEdge->getLength() / 2., "",
     844          880 :                                          tObject.getParameter().arrivalPos, "",
     845          880 :                                          tObject.getMaxSpeed(), nullptr, tObject.getVTypeParameter(), 0, now, items);
     846              :             }
     847          880 :             if (success) {
     848         2640 :                 for (const MSTransportableRouter::TripItem& it : items) {
     849         1760 :                     if (!it.edges.empty() && !edges.empty() && edges.back() == it.edges.front()) {
     850              :                         edges.pop_back();
     851              :                     }
     852         1760 :                     edges.insert(edges.end(), std::make_move_iterator(it.edges.begin()), std::make_move_iterator(it.edges.end()));
     853              :                 }
     854          880 :                 if (!edges.empty()) {
     855          880 :                     static_cast<MSPerson&>(tObject).replaceWalk(edges, tObject.getPositionOnLane(), 0, 1);
     856              :                 }
     857              :             } else {
     858              :                 // maybe the pedestrian model still finds a way (JuPedSim)
     859            0 :                 static_cast<MSPerson&>(tObject).replaceWalk({tObject.getEdge(), newEdge, lastEdge}, tObject.getPositionOnLane(), 0, 1);
     860              :             }
     861              :         }
     862         1020 :         if (!prohibited.empty()) {
     863           70 :             resetClosedEdges(hasReroutingDevice, tObject);
     864              :         }
     865              :     }
     866              :     return false; // XXX another interval could appear later but we would have to track whether the currenty interval was already used
     867        10095 : }
     868              : 
     869              : 
     870              : void
     871            1 : MSTriggeredRerouter::setUserMode(bool val) {
     872            1 :     myAmInUserMode = val;
     873            1 : }
     874              : 
     875              : 
     876              : void
     877            1 : MSTriggeredRerouter::setUserUsageProbability(double prob) {
     878            1 :     myUserProbability = prob;
     879            1 : }
     880              : 
     881              : 
     882              : bool
     883            0 : MSTriggeredRerouter::inUserMode() const {
     884            0 :     return myAmInUserMode;
     885              : }
     886              : 
     887              : 
     888              : double
     889         5886 : MSTriggeredRerouter::getProbability() const {
     890         5886 :     return myAmInUserMode ? myUserProbability : myProbability;
     891              : }
     892              : 
     893              : 
     894              : double
     895            0 : MSTriggeredRerouter::getUserProbability() const {
     896            0 :     return myUserProbability;
     897              : }
     898              : 
     899              : 
     900              : double
     901       115448 : MSTriggeredRerouter::getStoppingPlaceOccupancy(MSStoppingPlace* sp, const SUMOVehicle* veh) {
     902              :     return (sp->getElement() == SUMO_TAG_PARKING_AREA
     903       115448 :                     ? (double)dynamic_cast<MSParkingArea*>(sp)->getOccupancyIncludingRemoteReservations(veh)
     904           42 :                     : (double)sp->getStoppedVehicles().size());
     905              : }
     906              : 
     907              : 
     908              : double
     909       100276 : MSTriggeredRerouter::getLastStepStoppingPlaceOccupancy(MSStoppingPlace* sp, const SUMOVehicle* veh) {
     910              :     return (sp->getElement() == SUMO_TAG_PARKING_AREA
     911       100276 :                     ? (double)dynamic_cast<MSParkingArea*>(sp)->getLastStepOccupancyIncludingRemoteReservations(veh)
     912           42 :                     : (double)sp->getStoppedVehicles().size());
     913              : }
     914              : 
     915              : 
     916              : double
     917       318647 : MSTriggeredRerouter::getStoppingPlaceCapacity(MSStoppingPlace* sp) {
     918              :     if (myBlockedStoppingPlaces.count(sp) == 0) {
     919              :         return (double)(sp->getElement() == SUMO_TAG_PARKING_AREA
     920       318631 :                         ? dynamic_cast<MSParkingArea*>(sp)->getCapacity()
     921              :                         // assume only one vehicle at a time (for stationReroute)
     922              :                         : 1.);
     923              :     } else {
     924              :         return 0.;
     925              :     }
     926              : }
     927              : 
     928              : 
     929              : void
     930       106365 : MSTriggeredRerouter::rememberBlockedStoppingPlace(SUMOVehicle& veh, const MSStoppingPlace* parkingArea, bool blocked) {
     931       106365 :     veh.rememberBlockedParkingArea(parkingArea, blocked);
     932       106365 : }
     933              : 
     934              : 
     935              : void
     936       157127 : MSTriggeredRerouter::rememberStoppingPlaceScore(SUMOVehicle& veh, MSStoppingPlace* parkingArea, const std::string& score) {
     937       157127 :     veh.rememberParkingAreaScore(parkingArea, score);
     938       157127 : }
     939              : 
     940              : 
     941              : void
     942        35323 : MSTriggeredRerouter::resetStoppingPlaceScores(SUMOVehicle& veh) {
     943        35323 :     veh.resetParkingAreaScores();
     944        35323 : }
     945              : 
     946              : 
     947              : SUMOTime
     948        85825 : MSTriggeredRerouter::sawBlockedStoppingPlace(SUMOVehicle& veh, MSStoppingPlace* parkingArea, bool local) {
     949        85825 :     return veh.sawBlockedParkingArea(parkingArea, local);
     950              : }
     951              : 
     952              : 
     953              : int
     954        82279 : MSTriggeredRerouter::getNumberStoppingPlaceReroutes(SUMOVehicle& veh) {
     955        82279 :     return veh.getNumberParkingReroutes();
     956              : }
     957              : 
     958              : 
     959              : void
     960        35323 : MSTriggeredRerouter::setNumberStoppingPlaceReroutes(SUMOVehicle& veh, int value) {
     961        35323 :     veh.setNumberParkingReroutes(value);
     962        35323 : }
     963              : 
     964              : 
     965              : MSParkingArea*
     966       111440 : MSTriggeredRerouter::rerouteParkingArea(const MSTriggeredRerouter::RerouteInterval* rerouteDef,
     967              :                                         SUMOVehicle& veh, bool& newDestination, ConstMSEdgeVector& newRoute) {
     968       111440 :     MSStoppingPlace* destStoppingPlace = veh.getNextParkingArea();
     969       111440 :     if (destStoppingPlace == nullptr) {
     970              :         // not driving towards the right type of stop
     971              :         return nullptr;
     972              :     }
     973              :     std::vector<StoppingPlaceVisible> parks;
     974       329734 :     for (auto cand : rerouteDef->parkProbs.getVals()) {
     975       229358 :         if (cand.first->accepts(&veh)) {
     976       228542 :             parks.push_back(cand);
     977              :         }
     978              :     }
     979              :     StoppingPlaceParamMap_t addInput = {};
     980       200752 :     return dynamic_cast<MSParkingArea*>(rerouteStoppingPlace(destStoppingPlace, parks, rerouteDef->parkProbs.getProbs(), veh, newDestination, newRoute, addInput, rerouteDef->getClosed()));
     981       100376 : }
     982              : 
     983              : 
     984              : std::pair<const SUMOVehicle*, MSRailSignal*>
     985          183 : MSTriggeredRerouter::overtakingTrain(const SUMOVehicle& veh,
     986              :                                      ConstMSEdgeVector::const_iterator mainStart,
     987              :                                      const OvertakeLocation& oloc,
     988              :                                      double& netSaving) {
     989          183 :     const ConstMSEdgeVector& route = veh.getRoute().getEdges();
     990              :     const MSEdgeVector& main = oloc.main;
     991          183 :     const double vMax = veh.getMaxSpeed();
     992          366 :     const double prio = veh.getFloatParam(toString(SUMO_TAG_OVERTAKING_REROUTE) + ".prio", false, DEFAULT_PRIO_OVERTAKEN, false);
     993          183 :     MSVehicleControl& c = MSNet::getInstance()->getVehicleControl();
     994          437 :     for (MSVehicleControl::constVehIt it_veh = c.loadedVehBegin(); it_veh != c.loadedVehEnd(); ++it_veh) {
     995          307 :         const MSBaseVehicle* veh2 = dynamic_cast<const MSBaseVehicle*>((*it_veh).second);
     996          307 :         if (veh2->isOnRoad() && veh2->getMaxSpeed() > vMax) {
     997           93 :             const double arrivalDelay = veh2->getStopArrivalDelay();
     998          182 :             const double delay = MAX2(veh2->getStopDelay(), arrivalDelay == INVALID_DOUBLE ? 0 : arrivalDelay);
     999          279 :             if (delay > veh2->getFloatParam(toString(SUMO_TAG_OVERTAKING_REROUTE) + ".maxDelay", false, DEFAULT_MAXDELAY, false)) {
    1000              :                 continue;
    1001              :             }
    1002           89 :             const ConstMSEdgeVector& route2 = veh2->getRoute().getEdges();
    1003              :             auto itOnMain2 = route2.end();
    1004              :             int mainIndex = 0;
    1005          110 :             for (const MSEdge* m : main) {
    1006          105 :                 itOnMain2 = std::find(veh2->getCurrentRouteEdge(), route2.end(), m);
    1007          105 :                 if (itOnMain2 != route2.end()) {
    1008              :                     break;
    1009              :                 }
    1010           21 :                 mainIndex++;
    1011              :             }
    1012           89 :             if (itOnMain2 != route2.end() && itOnMain2 > veh2->getCurrentRouteEdge()) {
    1013              :                 auto itOnMain = mainStart + mainIndex;
    1014              :                 double timeToMain = 0;
    1015          371 :                 for (auto it = veh.getCurrentRouteEdge(); it != itOnMain; it++) {
    1016          290 :                     timeToMain += (*it)->getMinimumTravelTime(&veh);
    1017              :                 }
    1018              :                 // veh2 may be anywhere on the current edge so we have to discount
    1019           81 :                 double timeToMain2 = -veh2->getEdge()->getMinimumTravelTime(veh2) * veh2->getPositionOnLane() / veh2->getEdge()->getLength();
    1020              :                 double timeToLastSignal2 = timeToMain2;
    1021          562 :                 for (auto it = veh2->getCurrentRouteEdge(); it != itOnMain2; it++) {
    1022          481 :                     timeToMain2 += (*it)->getMinimumTravelTime(veh2);
    1023          481 :                     auto signal = getRailSignal(*it);
    1024          481 :                     if (signal) {
    1025              :                         timeToLastSignal2 = timeToMain2;
    1026              : #ifdef DEBUG_OVERTAKING
    1027              :                         std::cout << "   lastBeforeMain2 " << signal->getID() << "\n";
    1028              : #endif
    1029              :                     }
    1030              :                 }
    1031              :                 double exitMainTime = timeToMain;
    1032              :                 double exitMainBlockTime2 = timeToMain2;
    1033              :                 double commonTime = 0;
    1034              :                 double commonTime2 = 0;
    1035              :                 int nCommon = 0;
    1036              :                 auto exitMain2 = itOnMain2;
    1037              :                 const MSRailSignal* firstAfterMain = nullptr;
    1038              :                 const MSEdge* common = nullptr;
    1039           81 :                 double vMinCommon = (*itOnMain)->getVehicleMaxSpeed(&veh);
    1040           81 :                 double vMinCommon2 = (*itOnMain2)->getVehicleMaxSpeed(veh2);
    1041              :                 while (itOnMain2 != route2.end()
    1042          794 :                         && itOnMain != route.end()
    1043         1657 :                         && *itOnMain == *itOnMain2) {
    1044              :                     common = *itOnMain;
    1045          785 :                     commonTime += common->getMinimumTravelTime(&veh);
    1046          785 :                     commonTime2 += common->getMinimumTravelTime(veh2);
    1047          785 :                     vMinCommon = MIN2(vMinCommon, common->getVehicleMaxSpeed(&veh));
    1048          785 :                     vMinCommon2 = MIN2(vMinCommon2, common->getVehicleMaxSpeed(veh2));
    1049          785 :                     const bool onMain = nCommon < (int)main.size() - mainIndex;
    1050          785 :                     if (onMain) {
    1051          240 :                         exitMainTime = timeToMain + commonTime;
    1052              :                     }
    1053          785 :                     if (firstAfterMain == nullptr) {
    1054          480 :                         exitMainBlockTime2 = timeToMain2 + commonTime2;
    1055              :                     }
    1056          785 :                     auto signal = getRailSignal(common);
    1057          785 :                     if (signal) {
    1058          318 :                         if (!onMain && firstAfterMain == nullptr) {
    1059              :                             firstAfterMain = signal;
    1060              : #ifdef DEBUG_OVERTAKING
    1061              :                             std::cout << "   firstAfterMain " << signal->getID() << "\n";
    1062              : #endif
    1063              :                         }
    1064              :                     }
    1065          785 :                     nCommon++;
    1066              :                     itOnMain++;
    1067              :                     itOnMain2++;
    1068              :                 }
    1069           81 :                 const double vMaxLast = common->getVehicleMaxSpeed(&veh);
    1070           81 :                 const double vMaxLast2 = common->getVehicleMaxSpeed(veh2);
    1071           81 :                 commonTime += veh.getLength() / vMaxLast;
    1072           81 :                 exitMainBlockTime2 += veh2->getLength() / vMaxLast2;
    1073           81 :                 exitMain2 += MIN2(nCommon, (int)main.size() - mainIndex);
    1074           81 :                 double timeLoss2 = MAX2(0.0, timeToMain + veh.getLength() / oloc.siding.front()->getVehicleMaxSpeed(&veh) - timeToLastSignal2);
    1075           81 :                 const double saving = timeToMain + commonTime - (timeToMain2 + commonTime2) - timeLoss2;
    1076           81 :                 const double loss = exitMainBlockTime2 - exitMainTime;
    1077          162 :                 const double prio2 = veh2->getFloatParam(toString(SUMO_TAG_OVERTAKING_REROUTE) + ".prio", false, DEFAULT_PRIO_OVERTAKER, false);
    1078              :                 // losses from acceleration after stopping at a signal
    1079           81 :                 const double accelTimeLoss = loss > 0 ? 0.5 * vMinCommon / veh.getVehicleType().getCarFollowModel().getMaxAccel() : 0;
    1080           81 :                 const double accelTimeLoss2 = timeLoss2 > 0 ? 0.5 * vMinCommon2 / veh2->getVehicleType().getCarFollowModel().getMaxAccel() : 0;
    1081           81 :                 netSaving = prio2 * (saving - accelTimeLoss2) - prio * (loss + accelTimeLoss);
    1082              : #ifdef DEBUG_OVERTAKING
    1083              :                 std::cout << SIMTIME << " veh=" << veh.getID() << " veh2=" << veh2->getID()
    1084              :                           << " sidingStart=" << oloc.siding.front()->getID()
    1085              :                           << " ttm=" << timeToMain << " ttm2=" << timeToMain2
    1086              :                           << " nCommon=" << nCommon << " cT=" << commonTime << " cT2=" << commonTime2
    1087              :                           << " em=" << exitMainTime << " emb2=" << exitMainBlockTime2
    1088              :                           << " ttls2=" << timeToLastSignal2
    1089              :                           << " saving=" << saving << " loss=" << loss
    1090              :                           << " atl=" << accelTimeLoss << " atl2=" << accelTimeLoss2 << " tl2=" << timeLoss2
    1091              :                           << " prio=" << prio << " prio2=" << prio2 << " netSaving=" << netSaving << "\n";
    1092              : #endif
    1093           81 :                 if (netSaving > oloc.minSaving) {
    1094           53 :                     MSRailSignal* s = findSignal(veh2->getCurrentRouteEdge(), exitMain2);
    1095           53 :                     if (s != nullptr) {
    1096           53 :                         return std::make_pair(veh2, s);
    1097              :                     }
    1098              :                 }
    1099              :             }
    1100              :         }
    1101              :     }
    1102          130 :     return std::make_pair(nullptr, nullptr);
    1103              : }
    1104              : 
    1105              : 
    1106              : void
    1107           15 : MSTriggeredRerouter::checkStopSwitch(MSBaseVehicle& ego, const MSTriggeredRerouter::RerouteInterval* def) {
    1108              :     myBlockedStoppingPlaces.clear();
    1109              : #ifdef DEBUG_REROUTER
    1110              :     std::cout << SIMTIME << " " << getID() << " ego=" << ego.getID() << "\n";
    1111              : #endif
    1112           15 :     if (!ego.hasStops()) {
    1113            1 :         return;
    1114              :     }
    1115           15 :     const MSStop& stop = ego.getNextStop();
    1116           15 :     if (stop.reached || stop.joinTriggered || (stop.pars.arrival < 0 && stop.pars.until < 0)) {
    1117              :         return;
    1118              :     }
    1119           15 :     MSStoppingPlace* cur = nullptr;
    1120           30 :     for (MSStoppingPlace* sp : stop.getPlaces()) {
    1121           15 :         for (auto item : def->stopAlternatives) {
    1122           15 :             if (sp == item.first) {
    1123           15 :                 cur = sp;
    1124           15 :                 break;
    1125              :             }
    1126              :         }
    1127           15 :     }
    1128           15 :     if (cur == nullptr) {
    1129              :         return;
    1130              :     }
    1131           15 :     std::vector<const SUMOVehicle*> stopped = cur->getStoppedVehicles();
    1132              : #ifdef DEBUG_REROUTER
    1133              :     std::cout << SIMTIME << " " << getID() << " ego=" << ego.getID() << " stopped=" << toString(stopped) << "\n";
    1134              : #endif
    1135              :     SUMOTime stoppedDuration = -1;
    1136           15 :     if (stopped.empty()) {
    1137              :         /// look upstream for vehicles that stop on this lane before ego arrives
    1138            9 :         const MSLane& stopLane = cur->getLane();
    1139            9 :         MSVehicleControl& c = MSNet::getInstance()->getVehicleControl();
    1140           28 :         for (MSVehicleControl::constVehIt it_veh = c.loadedVehBegin(); it_veh != c.loadedVehEnd(); ++it_veh) {
    1141           19 :             const MSBaseVehicle* veh = dynamic_cast<const MSBaseVehicle*>((*it_veh).second);
    1142           19 :             if (veh->isOnRoad() && veh->hasStops()) {
    1143           19 :                 const MSStop& vehStop = veh->getNextStop();
    1144           19 :                 if (vehStop.pars.lane == stopLane.getID()) {
    1145              :                     myBlockedStoppingPlaces.insert(cur);
    1146           12 :                     if (veh->isStopped()) {
    1147              :                         // stopped somewhere else on the same lane
    1148            3 :                         stoppedDuration = MAX3((SUMOTime)0, stoppedDuration, veh->getStopDuration());
    1149              :                     } else {
    1150            9 :                         std::pair<double, double> timeDist = veh->estimateTimeToNextStop();
    1151            9 :                         SUMOTime timeTo = TIME2STEPS(timeDist.first);
    1152            9 :                         stoppedDuration = MAX3((SUMOTime)0, stoppedDuration, timeTo + vehStop.getMinDuration(SIMSTEP + timeTo));
    1153              :                     }
    1154              :                 }
    1155              :             }
    1156              :         }
    1157              :     } else {
    1158              :         stoppedDuration = 0;
    1159           12 :         for (const SUMOVehicle* veh : cur->getStoppedVehicles()) {
    1160            6 :             stoppedDuration = MAX2(stoppedDuration, veh->getStopDuration());
    1161            6 :         }
    1162              :     }
    1163           15 :     if (stoppedDuration < 0) {
    1164              :         return;
    1165              :     }
    1166              :     /// @todo: consider time for conflict veh to leave the block
    1167           15 :     const SUMOTime stopFree = SIMSTEP + stoppedDuration;
    1168           15 :     const SUMOTime scheduledArrival = stop.pars.arrival >= 0 ? stop.pars.arrival : stop.pars.until - stop.pars.duration;
    1169              : #ifdef DEBUG_REROUTER
    1170              :     std::cout << SIMTIME << " " << getID() << " ego=" << ego.getID() << " stopFree=" << stopFree << " scheduledArrival=" << time2string(scheduledArrival) << "\n";
    1171              : #endif
    1172           15 :     if (stopFree < scheduledArrival) {
    1173              :         // no conflict according to the schedule
    1174              :         return;
    1175              :     }
    1176           14 :     const SUMOTime estimatedArrival = SIMSTEP + (stop.pars.arrival >= 0
    1177           14 :                                       ? TIME2STEPS(ego.getStopArrivalDelay())
    1178           24 :                                       : TIME2STEPS(ego.getStopDelay()) - stop.pars.duration);
    1179              : #ifdef DEBUG_REROUTER
    1180              :     std::cout << SIMTIME << " " << getID() << " ego=" << ego.getID() << " stopFree=" << stopFree << " estimatedArrival=" << time2string(estimatedArrival) << "\n";
    1181              : #endif
    1182           14 :     if (stopFree < estimatedArrival) {
    1183              :         // no conflict when considering current delay
    1184              :         return;
    1185              :     }
    1186           14 :     const std::vector<double> probs(def->stopAlternatives.size(), 1.);
    1187              :     StoppingPlaceParamMap_t scores = {};
    1188              :     bool newDestination;
    1189              :     ConstMSEdgeVector newRoute;
    1190              :     // @todo: consider future conflicts caused by rerouting
    1191              :     // @todo: reject alternatives with large detour
    1192           14 :     const MSStoppingPlace* alternative = rerouteStoppingPlace(nullptr, def->stopAlternatives, probs, ego, newDestination, newRoute, scores);
    1193              : #ifdef DEBUG_REROUTER
    1194              :     std::cout << SIMTIME << " " << getID() << " ego=" << ego.getID() << " alternative=" << Named::getIDSecure(alternative) << "\n";
    1195              : #endif
    1196           14 :     if (alternative != nullptr) {
    1197              :         // @todo adapt plans of any riders
    1198              :         //for (MSTransportable* p : ego.getPersons()) {
    1199              :         //    p->rerouteParkingArea(ego.getNextParkingArea(), newParkingArea);
    1200              :         //}
    1201              : 
    1202           14 :         if (newDestination && ego.getParameter().arrivalPosProcedure != ArrivalPosDefinition::DEFAULT) {
    1203              :             // update arrival parameters
    1204            0 :             SUMOVehicleParameter* newParameter = new SUMOVehicleParameter();
    1205            0 :             *newParameter = ego.getParameter();
    1206            0 :             newParameter->arrivalPosProcedure = ArrivalPosDefinition::GIVEN;
    1207            0 :             newParameter->arrivalPos = alternative->getEndLanePosition();
    1208            0 :             ego.replaceParameter(newParameter);
    1209              :         }
    1210              : 
    1211           14 :         SUMOVehicleParameter::Stop newStop = stop.pars;
    1212           14 :         newStop.lane = alternative->getLane().getID();
    1213           14 :         newStop.startPos = alternative->getBeginLanePosition();
    1214           14 :         newStop.endPos = alternative->getEndLanePosition();
    1215           14 :         switch (alternative->getElement()) {
    1216            0 :             case SUMO_TAG_PARKING_AREA:
    1217              :                 newStop.parkingarea = alternative->getID();
    1218              :                 break;
    1219            0 :             case SUMO_TAG_CONTAINER_STOP:
    1220              :                 newStop.containerstop = alternative->getID();
    1221              :                 break;
    1222            0 :             case SUMO_TAG_CHARGING_STATION:
    1223              :                 newStop.chargingStation = alternative->getID();
    1224              :                 break;
    1225            0 :             case SUMO_TAG_OVERHEAD_WIRE_SEGMENT:
    1226              :                 newStop.overheadWireSegment = alternative->getID();
    1227              :                 break;
    1228           14 :             case SUMO_TAG_BUS_STOP:
    1229              :             case SUMO_TAG_TRAIN_STOP:
    1230              :             default:
    1231              :                 newStop.busstop = alternative->getID();
    1232              :         }
    1233              :         std::string errorMsg;
    1234           28 :         if (!ego.replaceStop(0, newStop, getID() + ":" + toString(SUMO_TAG_STATION_REROUTE), false, errorMsg)) {
    1235            0 :             WRITE_WARNING("Vehicle '" + ego.getID() + "' at rerouter '" + getID()
    1236              :                           + "' could not perform stationReroute to '" + alternative->getID()
    1237              :                           + "' reason=" + errorMsg + ", time=" + time2string(MSNet::getInstance()->getCurrentTimeStep()) + ".");
    1238              :         }
    1239           14 :     }
    1240           29 : }
    1241              : 
    1242              : 
    1243              : MSRailSignal*
    1244          152 : MSTriggeredRerouter::findSignal(ConstMSEdgeVector::const_iterator begin, ConstMSEdgeVector::const_iterator end) {
    1245          152 :     auto it = end;
    1246              :     do {
    1247              :         it--;
    1248          304 :         auto signal = getRailSignal(*it);
    1249          304 :         if (signal != nullptr) {
    1250          152 :             return signal;
    1251              :         }
    1252          152 :     } while (it != begin);
    1253              :     return nullptr;
    1254              : }
    1255              : 
    1256              : 
    1257              : MSRailSignal*
    1258         1570 : MSTriggeredRerouter::getRailSignal(const MSEdge* edge) {
    1259         1570 :     if (edge->getToJunction()->getType() == SumoXMLNodeType::RAIL_SIGNAL) {
    1260          732 :         for (const MSLink* link : edge->getLanes().front()->getLinkCont()) {
    1261          732 :             if (link->getTLLogic() != nullptr) {
    1262          732 :                 return dynamic_cast<MSRailSignal*>(const_cast<MSTrafficLightLogic*>(link->getTLLogic()));
    1263              :             }
    1264              :         }
    1265              :     }
    1266              :     return nullptr;
    1267              : }
    1268              : 
    1269              : bool
    1270      1193681 : MSTriggeredRerouter::applies(const SUMOTrafficObject& obj) const {
    1271      1193681 :     if (myVehicleTypes.empty() || myVehicleTypes.count(obj.getVehicleType().getOriginalID()) > 0) {
    1272      1193577 :         return true;
    1273              :     } else {
    1274          208 :         std::set<std::string> vTypeDists = MSNet::getInstance()->getVehicleControl().getVTypeDistributionMembership(obj.getVehicleType().getOriginalID());
    1275          104 :         for (auto vTypeDist : vTypeDists) {
    1276              :             if (myVehicleTypes.count(vTypeDist) > 0) {
    1277              :                 return true;
    1278              :             }
    1279              :         }
    1280          104 :         return false;
    1281              :     }
    1282              : }
    1283              : 
    1284              : 
    1285              : bool
    1286        75340 : MSTriggeredRerouter::affected(const std::set<SUMOTrafficObject::NumericalID>& edgeIndices, const MSEdgeVector& closed) {
    1287       102541 :     for (const MSEdge* const e : closed) {
    1288        42980 :         if (edgeIndices.count(e->getNumericalID()) > 0) {
    1289              :             return true;
    1290              :         }
    1291              :     }
    1292              :     return false;
    1293              : }
    1294              : 
    1295              : 
    1296              : void
    1297        26894 : MSTriggeredRerouter::checkParkingRerouteConsistency() {
    1298              :     // if a parkingArea is a rerouting target, it should generally have a
    1299              :     // rerouter on its edge or vehicles will be stuck there once it's full.
    1300              :     // The user should receive a Warning in this case
    1301              :     std::set<MSEdge*> parkingRerouterEdges;
    1302              :     std::map<MSParkingArea*, std::string, ComparatorIdLess> targetedParkingArea; // paID -> targetingRerouter
    1303        31573 :     for (const auto& rr : myInstances) {
    1304              :         bool hasParkingReroute = false;
    1305         9217 :         for (const RerouteInterval& interval : rr.second->myIntervals) {
    1306         4538 :             if (interval.parkProbs.getOverallProb() > 0) {
    1307              :                 hasParkingReroute = true;
    1308        18213 :                 for (const StoppingPlaceVisible& pav : interval.parkProbs.getVals()) {
    1309        31284 :                     targetedParkingArea[dynamic_cast<MSParkingArea*>(pav.first)] = rr.first;
    1310              :                 }
    1311              :             }
    1312              :         }
    1313         4679 :         if (hasParkingReroute) {
    1314         2571 :             parkingRerouterEdges.insert(rr.second->myEdges.begin(), rr.second->myEdges.end());
    1315              :         }
    1316              :     }
    1317        30227 :     for (const auto& item : targetedParkingArea) {
    1318         3333 :         if (parkingRerouterEdges.count(&item.first->getLane().getEdge()) == 0) {
    1319         1560 :             WRITE_WARNINGF(TL("ParkingArea '%' is targeted by rerouter '%' but doesn't have its own rerouter. This may cause parking search to abort."),
    1320              :                            item.first->getID(), item.second);
    1321              :         }
    1322              :     }
    1323        26894 : }
    1324              : 
    1325              : 
    1326              : void
    1327        44939 : MSTriggeredRerouter::resetClosedEdges(bool hasReroutingDevice, const SUMOTrafficObject& o) {
    1328              :     // getRouterTT without prohibitions removes previous prohibitions
    1329        44939 :     if (o.isVehicle()) {
    1330              :         hasReroutingDevice
    1331        89878 :         ? MSRoutingEngine::getRouterTT(o.getRNGIndex(), o.getVClass())
    1332        71473 :         : MSNet::getInstance()->getRouterTT(o.getRNGIndex());
    1333              :     } else {
    1334              :         hasReroutingDevice
    1335            0 :         ? MSRoutingEngine::getIntermodalRouterTT(o.getRNGIndex())
    1336            0 :         : MSNet::getInstance()->getIntermodalRouter(o.getRNGIndex(), 0);
    1337              :     }
    1338        44939 : }
    1339              : 
    1340              : /****************************************************************************/
        

Generated by: LCOV version 2.0-1