16namespace traffic_manager {
18using namespace constants::FrameMemory;
19using namespace constants::WorldInfoRefresh;
22 std::vector<float> longitudinal_PID_parameters,
23 std::vector<float> longitudinal_highway_PID_parameters,
24 std::vector<float> lateral_PID_parameters,
25 std::vector<float> lateral_highway_PID_parameters,
26 float perc_difference_from_limit,
27 cc::detail::EpisodeProxy &episode_proxy,
30 : longitudinal_PID_parameters(longitudinal_PID_parameters),
31 longitudinal_highway_PID_parameters(longitudinal_highway_PID_parameters),
32 lateral_PID_parameters(lateral_PID_parameters),
33 lateral_highway_PID_parameters(lateral_highway_PID_parameters),
35 episode_proxy(episode_proxy),
36 world(
cc::World(episode_proxy)),
70 longitudinal_PID_parameters,
71 longitudinal_highway_PID_parameters,
72 lateral_PID_parameters,
73 lateral_highway_PID_parameters,
88 alsm(
ALSM(registered_vehicles,
101 vehicle_light_stage)),
121 local_map = std::make_shared<InMemoryMap>(world_map);
124 if (!files.empty()) {
126 if (content.size() != 0) {
132 log_warning(
"fetching the Traffic Manager cache", files[0],
"from the server again");
135 local_map = std::make_shared<InMemoryMap>(world_map);
136 if (content.size() == 0 || !
local_map->Load(content)) {
137 local_map = std::make_shared<InMemoryMap>(world_map);
142 log_warning(
"No InMemoryMap cache found. Setting up local map. This may take a while...");
146 log_warning(
"No InMemoryMap cache found. Setting up local map. This may take a while...");
161 if (!synchronous_mode) {
171 if (!synchronous_mode && hybrid_physics_mode) {
172 TimePoint current_instance = chr::system_clock::now();
174 chr::duration<float> time_to_wait = chr::duration<float>(HYBRID_MODE_DT) - elapsed_time;
175 if (time_to_wait > chr::duration<float>(0.0f)) {
176 std::this_thread::sleep_for(time_to_wait);
185 if (!synchronous_mode) {
193 if (synchronous_mode ||
212 uint64_t growth_factor =
static_cast<uint64_t
>(
static_cast<float>(number_of_vehicles) *
INV_GROWTH_STEP_SIZE);
217 tl_frame.reserve(new_frame_capacity);
230 tl_frame.resize(number_of_vehicles);
240 for (
unsigned long index = 0u; index <
vehicle_id_list.size(); ++index) {
243 for (
unsigned long index = 0u; index <
vehicle_id_list.size(); ++index) {
252 for (
unsigned long index = 0u; index <
vehicle_id_list.size(); ++index) {
265 const bool any_skipped = std::any_of(
272 for (
unsigned long index = 0u; index <
control_frame.size(); ++index) {
281 registration_lock.unlock();
285 if (synchronous_mode) {
349 registration_lock.unlock();
368 const auto deadline = std::chrono::steady_clock::now() + simulator->GetNetworkingTimeout().to_chrono();
369 while (simulator->GetCurrentEpisodeId() != episode_id && std::chrono::steady_clock::now() < deadline) {
370 std::this_thread::sleep_for(std::chrono::milliseconds(10));
382 for (
auto actor : vehicle_list) {
389 std::vector<ActorId> actor_id_list;
390 for (
auto &actor : actor_list) {
534 for (
auto &elem : tl_to_freeze) {
535 if (!elem->IsFrozen() || elem->GetState() != TLS::Red) {
545 if (mode == previously_synchronous) {
549 if (!previously_synchronous) {
562 log_error(
"TrafficManagerLocal: worker thread present in synchronous mode; joining before async restart.");
std::size_t frame
Number of frames elapsed since the simulator was launched.
double elapsed_seconds
Simulated seconds elapsed since the beginning of the current episode.
const Timestamp & GetTimestamp() const
Get timestamp of this snapshot.
WorldSnapshot GetSnapshot() const
Return a snapshot of the world at this moment.
void ResetAllTrafficLights()
SharedPtr< Map > GetMap() const
Return the map that describes this world.
auto GetId() const noexcept
SharedPtrType Lock() const
Same as TryLock but never return nullptr.
float actor_active_distance
ALSM: Agent Lifecycle and State Managerment This class has functionality to update the local cache of...
void AddActor(const Actor actor)
void RemoveActor(const ActorId actor_id, const bool registered_actor)
std::vector< ActorId > GetIDList()
void Insert(std::vector< ActorPtr > actor_list)
This class has functionality to detect potential collision with a nearby actor.
void Update(const unsigned long index) override
This class has functionality to maintain a horizon of waypoints ahead of the vehicle for it to follow...
ActionBuffer ComputeActionBuffer(const ActorId &actor_id)
Action ComputeNextAction(const ActorId &actor_id)
void Update(const unsigned long index) override
void Update(const unsigned long index)
void SetCycleTimestamp(const cc::Timestamp ×tamp)
Pins one frame for the whole cycle; reading it per vehicle lets a frame land mid-cycle and skews the ...
void SetGlobalLargeVehicleWideTurn(const bool enable)
Method to enable/disable the wide-turn manoeuvre globally for all large vehicles.
void SetLaneOffset(const ActorPtr &actor, const float offset)
Method to set a lane offset displacement from the center line.
void SetKeepSlowLanePercentage(const ActorPtr &actor, const float percentage)
Method to set % to keep on the slow lane.
void SetImportedRoute(const ActorPtr &actor, const Route route, const bool empty_buffer)
Method to set our own imported route.
void SetHybridPhysicsRadius(const float radius)
Method to set hybrid physics radius.
void UpdateUploadPath(const ActorId &actor_id, const Path path)
Method to update an already set list of points.
void SetRandomLeftLaneChangePercentage(const ActorPtr &actor, const float percentage)
Method to set % to randomly do a left lane change.
void SetGlobalDistanceToLeadingVehicle(const float dist)
Method to set the distance to leading vehicle for all registered vehicles.
void UpdateImportedRoute(const ActorId &actor_id, const Route route)
Method to update an already set route.
void SetGlobalLaneOffset(float const offset)
Method to set a global lane offset displacement from the center line.
void SetDistanceToLeadingVehicle(const ActorPtr &actor, const float distance)
Method to specify how much distance a vehicle should maintain to the leading vehicle.
void SetForceLaneChange(const ActorPtr &actor, const bool direction)
Method to force lane change on a vehicle.
void SetPercentageRunningSign(const ActorPtr &actor, const float perc)
Method to set % to run any traffic sign.
void SetCustomPath(const ActorPtr &actor, const Path path, const bool empty_buffer)
Method to set our own imported path.
void RemoveImportedRoute(const ActorId &actor_id, const bool remove_path)
Method to remove a route.
void SetPercentageIgnoreVehicles(const ActorPtr &actor, const float perc)
Method to set % to ignore any vehicle.
void SetMaxBoundaries(const float lower, const float upper)
Method to set limits for boundaries when respawning vehicles.
void SetSynchronousModeTimeOutInMiliSecond(const double time)
Set Synchronous mode time out.
void SetHybridPhysicsMode(const bool mode_switch)
Method to set hybrid physics mode.
void SetCollisionDetection(const ActorPtr &reference_actor, const ActorPtr &other_actor, const bool detect_collision)
Method to set collision detection rules between vehicles.
void SetPercentageRunningLight(const ActorPtr &actor, const float perc)
Method to set % to run any traffic light.
void SetRespawnDormantVehicles(const bool mode_switch)
Method to set if we are automatically respawning vehicles.
void SetAutoLaneChange(const ActorPtr &actor, const bool enable)
Enable/disable automatic lane change on a vehicle.
void SetDesiredSpeed(const ActorPtr &actor, const float value)
Set a vehicle's exact desired velocity.
void RemoveUploadPath(const ActorId &actor_id, const bool remove_path)
Method to remove a list of points.
bool GetSynchronousMode() const
Method to get synchronous mode.
void SetGlobalPercentageSpeedDifference(float const percentage)
Set a global % decrease in velocity with respect to the speed limit.
void SetPercentageIgnoreWalkers(const ActorPtr &actor, const float perc)
Method to set % to ignore any vehicle.
void SetBoundariesRespawnDormantVehicles(const float lower_bound, const float upper_bound)
Method to set boundaries for respawning vehicles.
void SetRandomRightLaneChangePercentage(const ActorPtr &actor, const float percentage)
Method to set % to randomly do a right lane change.
void SetPercentageSpeedDifference(const ActorPtr &actor, const float percentage)
Set a vehicle's % decrease in velocity with respect to the speed limit.
void SetOSMMode(const bool mode_switch)
Method to set Open Street Map mode.
bool GetHybridPhysicsMode() const
Method to retrieve hybrid physics mode.
void SetLargeVehicleWideTurn(const ActorPtr &actor, const bool enable)
Method to enable/disable the wide-turn manoeuvre for a single large vehicle (bus/truck).
void SetSynchronousMode(const bool mode_switch=true)
Method to set synchronous mode.
void SetUpdateVehicleLights(const ActorPtr &actor, const bool do_update)
Method to set the automatic vehicle light state update flag.
This class has functionality for responding to traffic lights and managing entry into non-signalized ...
void Update(const unsigned long index) override
The function of this class is to integrate all the various stages of the traffic manager appropriatel...
void Reset(uint64_t episode_id)
To reset the traffic manager for the episode episode_id.
int registered_vehicles_state
State counter to track changes in registered actors.
LocalizationStage localization_stage
Various stages representing core operations of traffic manager.
TimePoint previous_update_instance
Time instance used to calculate dt in asynchronous mode.
void SetDistanceToLeadingVehicle(const ActorPtr &actor, const float distance)
Method to specify how much distance a vehicle should maintain to the leading vehicle.
void SetLaneOffset(const ActorPtr &actor, const float offset)
Method to set a lane offset displacement from the center line.
AtomicActorSet registered_vehicles
Set of all actors registered with traffic manager.
std::unique_ptr< std::thread > worker_thread
Single worker thread for sequential execution of sub-components.
void SetRespawnDormantVehicles(const bool mode_switch)
Method to set automatic respawn of dormant vehicles.
MotionPlanStage motion_plan_stage
void SetRandomLeftLaneChangePercentage(const ActorPtr &actor, const float percentage)
Method to set % to randomly do a left lane change.
uint64_t seed
Randomization seed.
void SetGlobalPercentageSpeedDifference(float const percentage)
Method to set a global % decrease in velocity with respect to the speed limit.
void SetupLocalMap()
Method to setup InMemoryMap.
void Start()
To start the TrafficManager.
TrafficLightStage traffic_light_stage
carla::client::detail::EpisodeProxy & GetEpisodeProxy()
Get CARLA episode information.
ControlFrame control_frame
Array to hold output data of motion planning.
Parameters parameters
Parameterization object.
std::vector< ActorId > vehicle_id_list
List of vehicles registered with the traffic manager in current update cycle.
bool CheckAllFrozen(TLGroup tl_to_freeze)
Method to check if all traffic lights are frozen in a group.
void UpdateImportedRoute(const ActorId &actor_id, const Route route)
Method to update an already set route.
void SetRandomRightLaneChangePercentage(const ActorPtr &actor, const float percentage)
Method to set % to randomly do a right lane change.
void SetPercentageIgnoreVehicles(const ActorPtr &actor, const float perc)
Method to specify the % chance of ignoring collisions with any vehicle.
BufferMap buffer_map
Structures to hold waypoint buffers for all vehicles.
void SetForceLaneChange(const ActorPtr &actor, const bool direction)
Method to force lane change on a vehicle.
void RemoveImportedRoute(const ActorId &actor_id, const bool remove_path)
Method to remove a route.
void SetKeepSlowLanePercentage(const ActorPtr &actor, const float percentage)
Method to set % to keep on the slow lane.
void SetBoundariesRespawnDormantVehicles(const float lower_bound, const float upper_bound)
Method to set boundaries to respawn of dormant vehicles.
TrackTraffic track_traffic
Object for tracking paths of the traffic vehicles.
TrafficManagerServer server
Traffic manager server instance.
size_t last_frame
Last processed frame.
Action GetNextAction(const ActorId &actor_id)
Method to get the vehicle's next action.
void UpdateUploadPath(const ActorId &actor_id, const Path path)
Method to update an already set list of points.
CollisionFrame collision_frame
Array to hold output data of collision avoidance.
rpc::EpisodeSettings episode_settings
Cached episode settings; they only change through world.apply_settings.
void SetHybridPhysicsMode(const bool mode_switch)
Method to set hybrid physics mode.
void SetCustomPath(const ActorPtr &actor, const Path path, const bool empty_buffer)
Method to set our own imported path.
void Run()
Initiates thread to run the TrafficManager sequentially.
TLFrame tl_frame
Array to hold output data of traffic light response.
TrafficManagerLocal(std::vector< float > longitudinal_PID_parameters, std::vector< float > longitudinal_highway_PID_parameters, std::vector< float > lateral_PID_parameters, std::vector< float > lateral_highway_PID_parameters, float perc_decrease_from_limit, cc::detail::EpisodeProxy &episode_proxy, uint16_t &RPCportTM)
Private constructor for singleton lifecycle management.
void SetPercentageRunningLight(const ActorPtr &actor, const float perc)
Method to specify the % chance of running any traffic light.
uint64_t current_reserved_capacity
Variable to keep track of currently reserved array space for frames.
LocalizationFrame localization_frame
Array to hold output data of localization stage.
void SetPercentageRunningSign(const ActorPtr &actor, const float perc)
Method to specify the % chance of running any traffic sign.
CollisionStage collision_stage
VehicleLightStage vehicle_light_stage
void SetCollisionDetection(const ActorPtr &reference_actor, const ActorPtr &other_actor, const bool detect_collision)
Method to set collision detection rules between vehicles.
void SetOSMMode(const bool mode_switch)
Method to set Open Street Map mode.
ActionBuffer GetActionBuffer(const ActorId &actor_id)
Method to get the vehicle's action buffer.
cc::World world
CARLA client and object.
bool SynchronousTick()
Method to provide synchronous tick.
std::vector< ActorId > GetRegisteredVehiclesIDs()
Get list of all registered vehicles.
void SetImportedRoute(const ActorPtr &actor, const Route route, const bool empty_buffer)
Method to set our own imported route.
LocalMapPtr local_map
Pointer to local map cache.
void SetMaxBoundaries(const float lower, const float upper)
Method to set limits for boundaries when respawning dormant vehicles.
void SetPercentageSpeedDifference(const ActorPtr &actor, const float percentage)
Method to set a vehicle's % decrease in velocity with respect to the speed limit.
void SetGlobalLaneOffset(float const offset)
Method to set a global lane offset displacement from the center line.
void SetDesiredSpeed(const ActorPtr &actor, const float value)
Set a vehicle's exact desired velocity.
void SetAutoLaneChange(const ActorPtr &actor, const bool enable)
Enable/disable automatic lane change on a vehicle.
carla::client::detail::EpisodeProxy episode_proxy
CARLA client connection object.
void SetLargeVehicleWideTurn(const ActorPtr &actor, const bool enable)
Method to enable/disable the wide-turn manoeuvre for a single large vehicle.
void SetGlobalDistanceToLeadingVehicle(const float distance)
Method to specify how much distance a vehicle should maintain to the Global leading vehicle.
virtual ~TrafficManagerLocal()
Destructor.
std::atomic< bool > run_traffic_manger
Switch to turn on / turn off traffic manager.
RandomGenerator random_device
Structure holding random devices per vehicle.
SimulationState simulation_state
Type containing the current state of all actors involved in the simulation.
void RemoveUploadPath(const ActorId &actor_id, const bool remove_path)
Method to remove a list of points.
uint64_t unwaited_control_batches
Starts at the limit so the first batch of an episode is waited for.
void SetPercentageIgnoreWalkers(const ActorPtr &actor, const float perc)
Method to specify the % chance of ignoring collisions with any walker.
void SetUpdateVehicleLights(const ActorPtr &actor, const bool do_update)
Method to set the automatic management of the vehicle lights.
void Stop()
To stop the TrafficManager.
double last_settings_update
Simulation time of the last episode settings refresh.
void RegisterVehicles(const std::vector< ActorPtr > &actor_list)
This method registers a vehicle with the traffic manager.
void UnregisterVehicles(const std::vector< ActorPtr > &actor_list)
This method unregisters a vehicle from traffic manager.
void SetGlobalLargeVehicleWideTurn(const bool enable)
Method to enable/disable the wide-turn manoeuvre globally for large vehicles.
void SetSynchronousMode(bool mode)
Method to switch traffic manager into synchronous execution.
void SetHybridPhysicsRadius(const float radius)
Method to set hybrid physics radius.
void Release()
To release the traffic manager.
void SetRandomDeviceSeed(const uint64_t _seed)
Method to set randomization seed.
void Step()
To do one step of the TrafficManager.
std::mutex registration_mutex
Mutex to prevent vehicle registration during frame array re-allocation.
void SetSynchronousModeTimeOutInMiliSecond(double time)
Method to set Tick timeout for synchronous execution.
This class has functionality for turning on/off the vehicle lights according to the current vehicle s...
void UpdateWorldInfo(const double current_time, const bool synchronous_mode)
Synchronous mode refreshes every step.
void Update(const unsigned long index) override
static const uint64_t GROWTH_STEP_SIZE
static const float INV_GROWTH_STEP_SIZE
static const uint64_t INITIAL_SIZE
bool IsRefreshDue(const double now, const double last, const double period)
Also true when the clock jumps backwards (new episode) or on NaN, so an unusable clock refreshes rath...
static const double EPISODE_SETTINGS_REFRESH_PERIOD
bool IsBatchSyncDue(const uint64_t unwaited_batches, const uint64_t limit)
static const uint64_t MAX_UNWAITED_CONTROL_BATCHES
static const std::chrono::milliseconds SNAPSHOT_POLL_PERIOD
std::vector< carla::SharedPtr< carla::client::TrafficLight > > TLGroup
std::vector< uint8_t > Route
std::vector< cg::Location > Path
std::pair< RoadOption, WaypointPtr > Action
std::vector< carla::rpc::Command > ControlFrame
chr::time_point< chr::system_clock, chr::nanoseconds > TimePoint
carla::SharedPtr< cc::Actor > ActorPtr
std::vector< Action > ActionBuffer
This file contains definitions of common data structures used in traffic manager.
std::shared_ptr< T > SharedPtr
static void log_error(Args &&... args)
static void log_warning(Args &&... args)