LCOV - code coverage report
Current view: top level - src/libsumo - Helper.h (source / functions) Coverage Total Hit
Test: lcov.info Lines: 100.0 % 5 5
Test Date: 2025-12-06 15:35:27 Functions: - 0 0

            Line data    Source code
       1              : /****************************************************************************/
       2              : // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
       3              : // Copyright (C) 2012-2025 German Aerospace Center (DLR) and others.
       4              : // This program and the accompanying materials are made available under the
       5              : // terms of the Eclipse Public License 2.0 which is available at
       6              : // https://www.eclipse.org/legal/epl-2.0/
       7              : // This Source Code may also be made available under the following Secondary
       8              : // Licenses when the conditions for such availability set forth in the Eclipse
       9              : // Public License 2.0 are satisfied: GNU General Public License, version 2
      10              : // or later which is available at
      11              : // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
      12              : // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
      13              : /****************************************************************************/
      14              : /// @file    Helper.h
      15              : /// @author  Robert Hilbrich
      16              : /// @author  Leonhard Luecken
      17              : /// @date    15.09.2017
      18              : ///
      19              : // C++ TraCI client API implementation
      20              : /****************************************************************************/
      21              : #pragma once
      22              : #include <vector>
      23              : #include <memory>
      24              : #include <libsumo/Subscription.h>
      25              : #include <microsim/MSLane.h>
      26              : #include <microsim/MSNet.h>
      27              : #include <microsim/traffic_lights/MSTLLogicControl.h>
      28              : #include <microsim/trigger/MSCalibrator.h>
      29              : #include <utils/vehicle/SUMOVehicleParameter.h>
      30              : 
      31              : 
      32              : // ===========================================================================
      33              : // class declarations
      34              : // ===========================================================================
      35              : class Position;
      36              : class PositionVector;
      37              : class RGBColor;
      38              : class MSEdge;
      39              : class SUMOTrafficObject;
      40              : class MSPerson;
      41              : class MSVehicle;
      42              : class MSBaseVehicle;
      43              : class MSVehicleType;
      44              : class MSStoppingPlace;
      45              : 
      46              : 
      47              : // ===========================================================================
      48              : // class definitions
      49              : // ===========================================================================
      50              : namespace libsumo {
      51              : 
      52              : /**
      53              : * @class Helper
      54              : * @brief C++ TraCI client API implementation
      55              : */
      56              : class Helper {
      57              : public:
      58              :     static void subscribe(const int commandId, const std::string& id, const std::vector<int>& variables,
      59              :                           const double beginTime, const double endTime, const libsumo::TraCIResults& params,
      60              :                           const int contextDomain = 0, const double range = 0.);
      61              : 
      62              :     static void handleSubscriptions(const SUMOTime t);
      63              : 
      64              :     static bool needNewSubscription(libsumo::Subscription& s, std::vector<Subscription>& subscriptions, libsumo::Subscription*& modifiedSubscription);
      65              : 
      66              :     static void clearSubscriptions();
      67              : 
      68              :     static Subscription* addSubscriptionFilter(SubscriptionFilterType filter);
      69              : 
      70              :     /// @brief helper functions
      71              :     static TraCIPositionVector makeTraCIPositionVector(const PositionVector& positionVector);
      72              :     static TraCIPosition makeTraCIPosition(const Position& position, const bool includeZ = false);
      73              :     static Position makePosition(const TraCIPosition& position);
      74              : 
      75              :     static PositionVector makePositionVector(const TraCIPositionVector& vector);
      76              :     static TraCIColor makeTraCIColor(const RGBColor& color);
      77              :     static RGBColor makeRGBColor(const TraCIColor& color);
      78              : 
      79              :     static MSEdge* getEdge(const std::string& edgeID);
      80              :     static const MSLane* getLaneChecking(const std::string& edgeID, int laneIndex, double pos);
      81              :     static std::pair<MSLane*, double> convertCartesianToRoadMap(const Position& pos, const SUMOVehicleClass vClass);
      82              :     static double getDrivingDistance(std::pair<const MSLane*, double>& roadPos1, std::pair<const MSLane*, double>& roadPos2);
      83              : 
      84              :     static MSBaseVehicle* getVehicle(const std::string& id);
      85              :     static MSPerson* getPerson(const std::string& id);
      86              :     static SUMOTrafficObject* getTrafficObject(int domain, const std::string& id);
      87              :     static const MSVehicleType& getVehicleType(const std::string& vehicleID);
      88              :     static MSTLLogicControl::TLSLogicVariants& getTLS(const std::string& id);
      89              :     static MSStoppingPlace* getStoppingPlace(const std::string& id, const SumoXMLTag type);
      90              : 
      91              :     static SUMOVehicleParameter::Stop buildStopParameters(const std::string& edgeOrStoppingPlaceID,
      92              :             double pos, int laneIndex, double startPos, int flags, double duration, double until);
      93              : 
      94              :     static TraCINextStopData buildStopData(const SUMOVehicleParameter::Stop& stopPar);
      95              : 
      96              :     static void findObjectShape(int domain, const std::string& id, PositionVector& shape);
      97              : 
      98              :     static void collectObjectsInRange(int domain, const PositionVector& shape, double range, std::set<const Named*>& into);
      99              :     static void collectObjectIDsInRange(int domain, const PositionVector& shape, double range, std::set<std::string>& into);
     100              : 
     101              :     /**
     102              :      * @brief Filter the given ID-Set (which was obtained from an R-Tree search)
     103              :      *        according to the filters set by the subscription or firstly build the object ID list if
     104              :      *        the filters rather demand searching along the road network than considering a geometric range.
     105              :      * @param[in] s Subscription which holds the filter specification to be applied
     106              :      * @param[in/out] objIDs Set of object IDs that is to be filtered. Result is stored in place.
     107              :      * @note Currently this assumes that the objects are vehicles.
     108              :      */
     109              :     static void applySubscriptionFilters(const Subscription& s, std::set<std::string>& objIDs);
     110              : 
     111              :     /**
     112              :      * @brief Apply the subscription filter "lanes": Only return vehicles on list of lanes relative to ego vehicle.
     113              :      *        Search all predecessor and successor lanes along the road network up until upstreamDist and downstreamDist,
     114              :      *        respectively,
     115              :      * @param[in] s Subscription which holds the filter specification to be applied.
     116              :      * @param[in/out] vehs Set of SUMO traffic objects into which the result is inserted.
     117              :      * @param[in] filterLanes Lane offsets to consider.
     118              :      * @param[in] downstreamDist Downstream distance.
     119              :      * @param[in] upstreamDist Upstream distance.
     120              :      * @param[in] disregardOppositeDirection Whether vehicles on opposite lanes shall be taken into account.
     121              :      */
     122              :     static void applySubscriptionFilterLanes(const Subscription& s, std::set<const SUMOTrafficObject*>& vehs, std::vector<int>& filterLanes,
     123              :             double downstreamDist, double upstreamDist, bool disregardOppositeDirection);
     124              : 
     125              :     /**
     126              :      * @brief Apply the subscription filter "turn": Gather upcoming junctions and vialanes within downstream
     127              :      *        distance and find approaching foes within foeDistToJunction.
     128              :      * @param[in] s Subscription which holds the filter specification to be applied.
     129              :      * @param[in/out] vehs Set of SUMO traffic objects into which the result is inserted.
     130              :      */
     131              :     static void applySubscriptionFilterTurn(const Subscription& s, std::set<const SUMOTrafficObject*>& vehs);
     132              : 
     133              :     static void applySubscriptionFilterFieldOfVision(const Subscription& s, std::set<std::string>& objIDs);
     134              : 
     135              :     /**
     136              :      * @brief Apply the subscription filter "lateral distance": Only return vehicles within the given lateral distance.
     137              :      *        Search myRoute (right-most lane) upstream and bestLanesCont downstream up until upstreamDist and
     138              :      *        downstreamDist, respectively.
     139              :      * @param[in] s Subscription which holds the filter specification to be applied.
     140              :      * @param[in/out] vehs Set of SUMO traffic objects into which the result is inserted.
     141              :      * @param[in] downstreamDist Downstream distance.
     142              :      * @param[in] upstreamDist Upstream distance.
     143              :      * @param[in] lateralDist Lateral distance.
     144              :      */
     145              :     static void applySubscriptionFilterLateralDistance(const Subscription& s, std::set<const SUMOTrafficObject*>& vehs, double downstreamDist,
     146              :             double upstreamDist, double lateralDist);
     147              : 
     148              :     static void applySubscriptionFilterLateralDistanceSinglePass(const Subscription& s,
     149              :             std::set<std::string>& objIDs,
     150              :             std::set<const SUMOTrafficObject*>& vehs,
     151              :             const std::vector<const MSLane*>& lanes,
     152              :             double posOnLane, double posLat, bool isDownstream);
     153              : 
     154              :     static void setRemoteControlled(MSVehicle* v, Position xyPos, MSLane* l, double pos, double posLat, double angle,
     155              :                                     int edgeOffset, ConstMSEdgeVector route, SUMOTime t);
     156              : 
     157              :     static void setRemoteControlled(MSPerson* p, Position xyPos, MSLane* l, double pos, double posLat, double angle,
     158              :                                     int edgeOffset, ConstMSEdgeVector route, SUMOTime t);
     159              : 
     160              :     /// @brief return number of remote-controlled entities
     161              :     static int postProcessRemoteControl();
     162              : 
     163              :     static void cleanup();
     164              : 
     165              :     static void registerStateListener();
     166              : 
     167              :     static const std::vector<std::string>& getVehicleStateChanges(const MSNet::VehicleState state);
     168              : 
     169              :     static const std::vector<std::string>& getTransportableStateChanges(const MSNet::TransportableState state);
     170              : 
     171              :     static void clearStateChanges();
     172              : 
     173              :     static MSCalibrator::AspiredState getCalibratorState(const MSCalibrator* c);
     174              : 
     175              :     /// @name functions for moveToXY
     176              :     /// @{
     177              :     static bool moveToXYMap(const Position& pos, double maxRouteDistance, bool mayLeaveNetwork, const std::string& origID,
     178              :                             const double angle, double speed, const ConstMSEdgeVector& currentRoute, const int routePosition,
     179              :                             const MSLane* currentLane, double currentLanePos, bool onRoad, SUMOVehicleClass vClass, double currentAngle, bool setLateralPos,
     180              :                             double& bestDistance, MSLane** lane, double& lanePos, int& routeOffset, ConstMSEdgeVector& edges);
     181              : 
     182              :     static bool moveToXYMap_matchingRoutePosition(const Position& pos, const std::string& origID,
     183              :             const ConstMSEdgeVector& currentRoute, int routeIndex,
     184              :             SUMOVehicleClass vClass, bool setLateralPos,
     185              :             double& bestDistance, MSLane** lane, double& lanePos, int& routeOffset);
     186              : 
     187              :     static bool findCloserLane(const MSEdge* edge, const Position& pos, SUMOVehicleClass vClass, double& bestDistance, MSLane** lane);
     188              : 
     189              :     /// @brief return the distance of pos from the area covered by this lane
     190              :     static double patchShapeDistance(const MSLane* lane, const Position& pos, double dist, bool wasPerpendicular);
     191              : 
     192              :     static int readDistanceRequest(tcpip::Storage& data, TraCIRoadPosition& roadPos, Position& pos);
     193              : 
     194              :     class LaneUtility {
     195              :     public:
     196              :         LaneUtility(double dist_, double perpendicularDist_, double lanePos_, double angleDiff_, bool ID_,
     197       200959 :                     bool onRoute_, bool sameEdge_, const MSEdge* prevEdge_, const MSEdge* nextEdge_) :
     198       200959 :             dist(dist_), perpendicularDist(perpendicularDist_), lanePos(lanePos_), angleDiff(angleDiff_), ID(ID_),
     199       200959 :             onRoute(onRoute_), sameEdge(sameEdge_), prevEdge(prevEdge_), nextEdge(nextEdge_) {}
     200       200959 :         ~LaneUtility() {}
     201              : 
     202              :         double dist;
     203              :         double perpendicularDist;
     204              :         double lanePos;
     205              :         double angleDiff;
     206              :         bool ID;
     207              :         bool onRoute;
     208              :         bool sameEdge;
     209              :         const MSEdge* prevEdge;
     210              :         const MSEdge* nextEdge;
     211              :     };
     212              :     /// @}
     213              : 
     214         6504 :     class SubscriptionWrapper final : public VariableWrapper {
     215              :     public:
     216              :         SubscriptionWrapper(VariableWrapper::SubscriptionHandler handler, SubscriptionResults& into, ContextSubscriptionResults& context);
     217              :         void setContext(const std::string* const refID);
     218              :         void clear();
     219              :         bool wrapConnectionVector(const std::string& objID, const int variable, const std::vector<TraCIConnection>& value);
     220              :         bool wrapDouble(const std::string& objID, const int variable, const double value);
     221              :         bool wrapInt(const std::string& objID, const int variable, const int value);
     222              :         bool wrapString(const std::string& objID, const int variable, const std::string& value);
     223              :         bool wrapStringList(const std::string& objID, const int variable, const std::vector<std::string>& value);
     224              :         bool wrapDoubleList(const std::string& objID, const int variable, const std::vector<double>& value);
     225              :         bool wrapPosition(const std::string& objID, const int variable, const TraCIPosition& value);
     226              :         bool wrapPositionVector(const std::string& objID, const int variable, const TraCIPositionVector& value);
     227              :         bool wrapColor(const std::string& objID, const int variable, const TraCIColor& value);
     228              :         bool wrapStringDoublePair(const std::string& objID, const int variable, const std::pair<std::string, double>& value);
     229              :         bool wrapStringDoublePairList(const std::string& objID, const int variable, const std::vector<std::pair<std::string, double> >& value);
     230              :         bool wrapStringPair(const std::string& objID, const int variable, const std::pair<std::string, std::string>& value);
     231              :         bool wrapIntPair(const std::string& objID, const int variable, const std::pair<int, int>& value);
     232              :         bool wrapStage(const std::string& objID, const int variable, const TraCIStage& value);
     233              :         bool wrapReservationVector(const std::string& objID, const int variable, const std::vector<TraCIReservation>& value);
     234              :         bool wrapLogicVector(const std::string& objID, const int variable, const std::vector<TraCILogic>& value);
     235              :         bool wrapLinkVectorVector(const std::string& objID, const int variable, const std::vector<std::vector<TraCILink> >& value);
     236              :         bool wrapSignalConstraintVector(const std::string& objID, const int variable, const std::vector<TraCISignalConstraint>& value);
     237              :         bool wrapJunctionFoeVector(const std::string& objID, const int variable, const std::vector<TraCIJunctionFoe>& value);
     238              :         bool wrapNextStopDataVector(const std::string& objID, const int variable, const std::vector<TraCINextStopData>& value);
     239              :         bool wrapVehicleDataVector(const std::string& objID, const int variable, const std::vector<TraCIVehicleData>& value);
     240              :         bool wrapBestLanesDataVector(const std::string& objID, const int variable, const std::vector<TraCIBestLanesData>& value);
     241              :         bool wrapNextTLSDataVector(const std::string& objID, const int variable, const std::vector<TraCINextTLSData>& value);
     242              :         void empty(const std::string& objID);
     243              :     private:
     244              :         SubscriptionResults& myResults;
     245              :         ContextSubscriptionResults& myContextResults;
     246              :         SubscriptionResults* myActiveResults;
     247              :     private:
     248              :         /// @brief Invalidated assignment operator
     249              :         SubscriptionWrapper& operator=(const SubscriptionWrapper& s) = delete;
     250              :     };
     251              : 
     252              : private:
     253              :     static void handleSingleSubscription(const Subscription& s);
     254              : 
     255              :     /// @brief Adds lane coverage information from newLaneCoverage into aggregatedLaneCoverage
     256              :     /// @param[in/out] aggregatedLaneCoverage - aggregated lane coverage info, to which the new will be added
     257              :     /// @param[in] newLaneCoverage - new lane coverage to be added
     258              :     /// @todo Disjunct ranges are not handled (LaneCoverageInfo definition would need to allow several intervals per lane) but
     259              :     ///       the intermediate range is simply assimilated.
     260              :     static void fuseLaneCoverage(std::shared_ptr<LaneCoverageInfo> aggregatedLaneCoverage, const std::shared_ptr<LaneCoverageInfo> newLaneCoverage);
     261              : 
     262              :     static void debugPrint(const SUMOTrafficObject* veh);
     263              : 
     264              : private:
     265              :     class VehicleStateListener : public MSNet::VehicleStateListener {
     266              :     public:
     267              :         void vehicleStateChanged(const SUMOVehicle* const vehicle, MSNet::VehicleState to, const std::string& info = "");
     268              :         /// @brief Changes in the states of simulated vehicles
     269              :         std::map<MSNet::VehicleState, std::vector<std::string> > myVehicleStateChanges;
     270              :     };
     271              : 
     272              :     class TransportableStateListener : public MSNet::TransportableStateListener {
     273              :     public:
     274              :         void transportableStateChanged(const MSTransportable* const transportable, MSNet::TransportableState to, const std::string& info = "");
     275              :         /// @brief Changes in the states of simulated transportables
     276              :         std::map<MSNet::TransportableState, std::vector<std::string> > myTransportableStateChanges;
     277              :     };
     278              : 
     279              :     /// @brief The list of known, still valid subscriptions
     280              :     static std::vector<Subscription> mySubscriptions;
     281              : 
     282              :     /// @brief The last context subscription
     283              :     static Subscription* myLastContextSubscription;
     284              : 
     285              :     /// @brief Map of commandIds -> their executors; applicable if the executor applies to the method footprint
     286              :     static std::map<int, std::shared_ptr<VariableWrapper> > myWrapper;
     287              : 
     288              :     /// @brief Changes in the states of simulated vehicles
     289              :     static VehicleStateListener myVehicleStateListener;
     290              : 
     291              :     /// @brief Changes in the states of simulated transportables
     292              :     static TransportableStateListener myTransportableStateListener;
     293              : 
     294              :     /// @brief A lookup tree of lanes
     295              :     static LANE_RTREE_QUAL* myLaneTree;
     296              : 
     297              :     static std::map<std::string, MSVehicle*> myRemoteControlledVehicles;
     298              :     static std::map<std::string, MSPerson*> myRemoteControlledPersons;
     299              : 
     300              :     /// @brief invalidated standard constructor
     301              :     Helper() = delete;
     302              : };
     303              : 
     304              : }
        

Generated by: LCOV version 2.0-1