CARLA
TrafficManagerLocal.h
Go to the documentation of this file.
1 // Copyright (c) 2020 Computer Vision Center (CVC) at the Universitat Autonoma
2 // de Barcelona (UAB).
3 //
4 // This work is licensed under the terms of the MIT license.
5 // For a copy, see <https://opensource.org/licenses/MIT>.
6 
7 #pragma once
8 
9 #include <atomic>
10 #include <chrono>
11 #include <mutex>
12 #include <thread>
13 #include <vector>
14 
17 #include "carla/client/World.h"
18 #include "carla/Memory.h"
19 #include "carla/rpc/Command.h"
20 
29 
35 
36 namespace carla {
37 namespace traffic_manager {
38 
39 namespace chr = std::chrono;
40 
41 using namespace std::chrono_literals;
42 
43 using TimePoint = chr::time_point<chr::system_clock, chr::nanoseconds>;
44 using TLGroup = std::vector<carla::SharedPtr<carla::client::TrafficLight>>;
45 using LocalMapPtr = std::shared_ptr<InMemoryMap>;
47 
48 /// The function of this class is to integrate all the various stages of
49 /// the traffic manager appropriately using messengers.
51 
52 private:
53  /// PID controller parameters.
54  std::vector<float> longitudinal_PID_parameters;
56  std::vector<float> lateral_PID_parameters;
57  std::vector<float> lateral_highway_PID_parameters;
58  /// CARLA client connection object.
60  /// CARLA client and object.
62  /// Set of all actors registered with traffic manager.
64  /// State counter to track changes in registered actors.
66  /// List of vehicles registered with the traffic manager in
67  /// current update cycle.
68  std::vector<ActorId> vehicle_id_list;
69  /// Pointer to local map cache.
71  /// Structures to hold waypoint buffers for all vehicles.
73  /// Object for tracking paths of the traffic vehicles.
75  /// Type containing the current state of all actors involved in the simulation.
77  /// Time instance used to calculate dt in asynchronous mode.
79  /// Parameterization object.
81  /// Array to hold output data of localization stage.
83  /// Array to hold output data of collision avoidance.
85  /// Array to hold output data of traffic light response.
87  /// Array to hold output data of motion planning.
89  /// Variable to keep track of currently reserved array space for frames.
90  uint64_t current_reserved_capacity {0u};
91  /// Various stages representing core operations of traffic manager.
98  /// Traffic manager server instance.
100  /// Switch to turn on / turn off traffic manager.
101  std::atomic<bool> run_traffic_manger{true};
102  /// Flags to signal step begin and end.
103  std::atomic<bool> step_begin{false};
104  std::atomic<bool> step_end{false};
105  /// Mutex for progressing synchronous execution.
107  /// Condition variables for progressing synchronous execution.
108  std::condition_variable step_begin_trigger;
109  std::condition_variable step_end_trigger;
110  /// Single worker thread for sequential execution of sub-components.
111  std::unique_ptr<std::thread> worker_thread;
112  /// Randomization seed.
113  uint64_t seed {static_cast<uint64_t>(time(NULL))};
114  /// Structure holding random devices per vehicle.
115  RandomGenerator random_device = RandomGenerator(seed);
116  std::vector<ActorId> marked_for_removal;
117  /// Mutex to prevent vehicle registration during frame array re-allocation.
118  std::mutex registration_mutex;
119 
120  /// Method to check if all traffic lights are frozen in a group.
121  bool CheckAllFrozen(TLGroup tl_to_freeze);
122 
123 public:
124  /// Private constructor for singleton lifecycle management.
125  TrafficManagerLocal(std::vector<float> longitudinal_PID_parameters,
126  std::vector<float> longitudinal_highway_PID_parameters,
127  std::vector<float> lateral_PID_parameters,
128  std::vector<float> lateral_highway_PID_parameters,
129  float perc_decrease_from_limit,
130  cc::detail::EpisodeProxy &episode_proxy,
131  uint16_t &RPCportTM);
132 
133  /// Destructor.
134  virtual ~TrafficManagerLocal();
135 
136  /// Method to setup InMemoryMap.
137  void SetupLocalMap();
138 
139  /// To start the TrafficManager.
140  void Start();
141 
142  /// Initiates thread to run the TrafficManager sequentially.
143  void Run();
144 
145  /// To stop the TrafficManager.
146  void Stop();
147 
148  /// To release the traffic manager.
149  void Release();
150 
151  /// To reset the traffic manager.
152  void Reset();
153 
154  /// This method registers a vehicle with the traffic manager.
155  void RegisterVehicles(const std::vector<ActorPtr> &actor_list);
156 
157  /// This method unregisters a vehicle from traffic manager.
158  void UnregisterVehicles(const std::vector<ActorPtr> &actor_list);
159 
160  /// Method to set a vehicle's % decrease in velocity with respect to the speed limit.
161  /// If less than 0, it's a % increase.
162  void SetPercentageSpeedDifference(const ActorPtr &actor, const float percentage);
163 
164  /// Set a vehicle's exact desired velocity.
165  void SetDesiredSpeed(const ActorPtr &actor, const float value);
166 
167  /// Method to set a global % decrease in velocity with respect to the speed limit.
168  /// If less than 0, it's a % increase.
169  void SetGlobalPercentageSpeedDifference(float const percentage);
170 
171  /// Method to set a lane offset displacement from the center line.
172  /// Positive values imply a right offset while negative ones mean a left one.
173  void SetLaneOffset(const ActorPtr &actor, const float offset);
174 
175  /// Method to set a global lane offset displacement from the center line.
176  /// Positive values imply a right offset while negative ones mean a left one.
177  void SetGlobalLaneOffset(float const offset);
178 
179  /// Method to set the automatic management of the vehicle lights
180  void SetUpdateVehicleLights(const ActorPtr &actor, const bool do_update);
181 
182  /// Method to set collision detection rules between vehicles.
183  void SetCollisionDetection(const ActorPtr &reference_actor, const ActorPtr &other_actor, const bool detect_collision);
184 
185  /// Method to force lane change on a vehicle.
186  /// Direction flag can be set to true for left and false for right.
187  void SetForceLaneChange(const ActorPtr &actor, const bool direction);
188 
189  /// Enable/disable automatic lane change on a vehicle.
190  void SetAutoLaneChange(const ActorPtr &actor, const bool enable);
191 
192  /// Method to specify how much distance a vehicle should maintain to
193  /// the leading vehicle.
194  void SetDistanceToLeadingVehicle(const ActorPtr &actor, const float distance);
195 
196  /// Method to specify the % chance of ignoring collisions with any walker.
197  void SetPercentageIgnoreWalkers(const ActorPtr &actor, const float perc);
198 
199  /// Method to specify the % chance of ignoring collisions with any vehicle.
200  void SetPercentageIgnoreVehicles(const ActorPtr &actor, const float perc);
201 
202  /// Method to specify the % chance of running any traffic light.
203  void SetPercentageRunningLight(const ActorPtr &actor, const float perc);
204 
205  /// Method to specify the % chance of running any traffic sign.
206  void SetPercentageRunningSign(const ActorPtr &actor, const float perc);
207 
208  /// Method to switch traffic manager into synchronous execution.
209  void SetSynchronousMode(bool mode);
210 
211  /// Method to set Tick timeout for synchronous execution.
212  void SetSynchronousModeTimeOutInMiliSecond(double time);
213 
214  /// Method to provide synchronous tick.
215  bool SynchronousTick();
216 
217  /// Get CARLA episode information.
218  carla::client::detail::EpisodeProxy &GetEpisodeProxy();
219 
220  /// Get list of all registered vehicles.
221  std::vector<ActorId> GetRegisteredVehiclesIDs();
222 
223  /// Method to specify how much distance a vehicle should maintain to
224  /// the Global leading vehicle.
225  void SetGlobalDistanceToLeadingVehicle(const float distance);
226 
227  /// Method to set % to keep on the right lane.
228  void SetKeepRightPercentage(const ActorPtr &actor, const float percentage);
229 
230  /// Method to set % to randomly do a left lane change.
231  void SetRandomLeftLaneChangePercentage(const ActorPtr &actor, const float percentage);
232 
233  /// Method to set % to randomly do a right lane change.
234  void SetRandomRightLaneChangePercentage(const ActorPtr &actor, const float percentage);
235 
236  /// Method to set hybrid physics mode.
237  void SetHybridPhysicsMode(const bool mode_switch);
238 
239  /// Method to set hybrid physics radius.
240  void SetHybridPhysicsRadius(const float radius);
241 
242  /// Method to set randomization seed.
243  void SetRandomDeviceSeed(const uint64_t _seed);
244 
245  /// Method to set Open Street Map mode.
246  void SetOSMMode(const bool mode_switch);
247 
248  /// Method to set our own imported path.
249  void SetCustomPath(const ActorPtr &actor, const Path path, const bool empty_buffer);
250 
251  /// Method to remove a list of points.
252  void RemoveUploadPath(const ActorId &actor_id, const bool remove_path);
253 
254  /// Method to update an already set list of points.
255  void UpdateUploadPath(const ActorId &actor_id, const Path path);
256 
257  /// Method to set our own imported route.
258  void SetImportedRoute(const ActorPtr &actor, const Route route, const bool empty_buffer);
259 
260  /// Method to remove a route.
261  void RemoveImportedRoute(const ActorId &actor_id, const bool remove_path);
262 
263  /// Method to update an already set route.
264  void UpdateImportedRoute(const ActorId &actor_id, const Route route);
265 
266  /// Method to set automatic respawn of dormant vehicles.
267  void SetRespawnDormantVehicles(const bool mode_switch);
268 
269  /// Method to set boundaries to respawn of dormant vehicles.
270  void SetBoundariesRespawnDormantVehicles(const float lower_bound, const float upper_bound);
271 
272  /// Method to set limits for boundaries when respawning dormant vehicles.
273  void SetMaxBoundaries(const float lower, const float upper);
274 
275  /// Method to get the vehicle's next action.
276  Action GetNextAction(const ActorId &actor_id);
277 
278  /// Method to get the vehicle's action buffer.
279  ActionBuffer GetActionBuffer(const ActorId &actor_id);
280 
281  void ShutDown() {};
282 };
283 
284 } // namespace traffic_manager
285 } // namespace carla
CollisionFrame collision_frame
Array to hold output data of collision avoidance.
TrafficManagerServer server
Traffic manager server instance.
std::vector< carla::rpc::Command > ControlFrame
carla::SharedPtr< cc::Actor > ActorPtr
std::vector< bool > TLFrame
std::vector< float > longitudinal_PID_parameters
PID controller parameters.
chr::time_point< chr::system_clock, chr::nanoseconds > TimePoint
std::condition_variable step_begin_trigger
Condition variables for progressing synchronous execution.
std::vector< cg::Location > Path
std::shared_ptr< InMemoryMap > LocalMapPtr
Definition: ALSM.h:36
This class holds the state of all the vehicles in the simlation.
This file contains definitions of common data structures used in traffic manager. ...
Definition: Carla.cpp:133
std::unordered_map< carla::ActorId, Buffer > BufferMap
ALSM: Agent Lifecycle and State Managerment This class has functionality to update the local cache of...
Definition: ALSM.h:41
Parameters parameters
Parameterization object.
std::vector< carla::SharedPtr< carla::client::TrafficLight > > TLGroup
std::pair< RoadOption, WaypointPtr > Action
carla::client::detail::EpisodeProxy episode_proxy
CARLA client connection object.
std::mutex step_execution_mutex
Mutex for progressing synchronous execution.
SimulationState simulation_state
Type containing the current state of all actors involved in the simulation.
carla::ActorId ActorId
cc::World world
CARLA client and object.
AtomicActorSet registered_vehicles
Set of all actors registered with traffic manager.
The function of this class is to integrate all the various stages of the traffic manager appropriatel...
std::vector< uint8_t > Route
This class has functionality for responding to traffic lights and managing entry into non-signalized ...
std::mutex registration_mutex
Mutex to prevent vehicle registration during frame array re-allocation.
std::vector< ActorId > vehicle_id_list
List of vehicles registered with the traffic manager in current update cycle.
TimePoint previous_update_instance
Time instance used to calculate dt in asynchronous mode.
ControlFrame control_frame
Array to hold output data of motion planning.
BufferMap buffer_map
Structures to hold waypoint buffers for all vehicles.
TrackTraffic track_traffic
Object for tracking paths of the traffic vehicles.
The function of this class is to integrate all the various stages of the traffic manager appropriatel...
std::vector< LocalizationData > LocalizationFrame
TLFrame tl_frame
Array to hold output data of traffic light response.
LocalizationFrame localization_frame
Array to hold output data of localization stage.
LocalMapPtr local_map
Pointer to local map cache.
LocalizationStage localization_stage
Various stages representing core operations of traffic manager.
EpisodeProxyImpl< EpisodeProxyPointerType::Strong > EpisodeProxy
Definition: EpisodeProxy.h:69
int registered_vehicles_state
State counter to track changes in registered actors.
This class has functionality to maintain a horizon of waypoints ahead of the vehicle for it to follow...
std::unique_ptr< std::thread > worker_thread
Single worker thread for sequential execution of sub-components.
std::vector< Action > ActionBuffer
This class has functionality for turning on/off the vehicle lights according to the current vehicle s...
This class has functionality to detect potential collision with a nearby actor.
std::vector< CollisionHazardData > CollisionFrame