CARLA
Loading...
Searching...
No Matches
ALSM.cpp
Go to the documentation of this file.
1
2#include <algorithm>
3#include <cctype>
4#include <string>
5
6#include "boost/pointer_cast.hpp"
7
8#include "carla/Logging.h"
11#include "carla/client/Walker.h"
12
16
18
19namespace carla {
20namespace traffic_manager {
21
51
53
54 bool hybrid_physics_mode = parameters.GetHybridPhysicsMode();
55
56 std::set<ActorId> world_vehicle_ids;
57 std::set<ActorId> world_pedestrian_ids;
58 std::vector<ActorId> unregistered_list_to_be_deleted;
59
60 current_timestamp = world.GetSnapshot().GetTimestamp();
61 ActorList world_actors = world.GetActors();
62
63 // Find destroyed actors and perform clean up.
64 const ALSM::DestroyeddActors destroyed_actors = IdentifyDestroyedActors(world_actors);
65
66 const ActorIdSet &destroyed_registered = destroyed_actors.first;
67 for (const auto &deletion_id: destroyed_registered) {
68 RemoveActor(deletion_id, true);
69 }
70
71 const ActorIdSet &destroyed_unregistered = destroyed_actors.second;
72 for (auto deletion_id : destroyed_unregistered) {
73 RemoveActor(deletion_id, false);
74 }
75
76 // Invalidate hero actor if it is not alive anymore.
77 if (hero_actors.size() != 0u) {
78 ActorIdSet hero_actors_to_delete;
79 for (auto &hero_actor_info: hero_actors) {
80 if (destroyed_unregistered.find(hero_actor_info.first) != destroyed_unregistered.end()) {
81 hero_actors_to_delete.insert(hero_actor_info.first);
82 }
83 if (destroyed_registered.find(hero_actor_info.first) != destroyed_registered.end()) {
84 hero_actors_to_delete.insert(hero_actor_info.first);
85 }
86 }
87
88 for (auto &deletion_id: hero_actors_to_delete) {
89 hero_actors.erase(deletion_id);
90 }
91 }
92
93 // Scan for new unregistered actors.
94 IdentifyNewActors(world_actors);
95
96 // Update dynamic state and static attributes for all registered vehicles.
97 ALSM::IdleInfo max_idle_time = std::make_pair(0u, current_timestamp.elapsed_seconds);
98 UpdateRegisteredActorsData(hybrid_physics_mode, max_idle_time);
99
100 // Destroy registered vehicle if stuck at a location for too long.
101 if (IsVehicleStuck(max_idle_time.first)
102 && (current_timestamp.elapsed_seconds - elapsed_last_actor_destruction) > DELTA_TIME_BETWEEN_DESTRUCTIONS
103 && hero_actors.find(max_idle_time.first) == hero_actors.end()) {
104 registered_vehicles.Destroy(max_idle_time.first);
105 RemoveActor(max_idle_time.first, true);
107 }
108
109 // Destorying vehicles for marked for removal by stages.
110 if (parameters.GetOSMMode()) {
111 for (const ActorId& actor_id: marked_for_removal) {
113 RemoveActor(actor_id, true);
114 }
115 marked_for_removal.clear();
116 }
117
118 // Update dynamic state and static attributes for unregistered actors.
120}
121
122void ALSM::IdentifyNewActors(const ActorList &actor_list) {
123 for (auto iter = actor_list->begin(); iter != actor_list->end(); ++iter) {
124 ActorPtr actor = *iter;
125 ActorId actor_id = actor->GetId();
126 // Identify any new hero vehicle
127 if (actor->GetTypeId().front() == 'v') {
128 if (hero_actors.size() == 0u || hero_actors.find(actor_id) == hero_actors.end()) {
129 for (auto&& attribute: actor->GetAttributes()) {
130 if (attribute.GetId() == "role_name" && attribute.GetValue() == "hero") {
131 hero_actors.insert({actor_id, actor});
132 }
133 }
134 }
135 }
136 if (!registered_vehicles.Contains(actor_id)
137 && unregistered_actors.find(actor_id) == unregistered_actors.end()) {
138
139 unregistered_actors.insert({actor_id, actor});
140 }
141 }
142}
143
145
146 ALSM::DestroyeddActors destroyed_actors;
147 ActorIdSet &deleted_registered = destroyed_actors.first;
148 ActorIdSet &deleted_unregistered = destroyed_actors.second;
149
150 // Building hash set of actors present in current frame.
151 ActorIdSet current_actors;
152 for (auto iter = actor_list->begin(); iter != actor_list->end(); ++iter) {
153 current_actors.insert((*iter)->GetId());
154 }
155
156 // Searching for destroyed registered actors.
157 std::vector<ActorId> registered_ids = registered_vehicles.GetIDList();
158 for (const ActorId &actor_id : registered_ids) {
159 if (current_actors.find(actor_id) == current_actors.end()) {
160 deleted_registered.insert(actor_id);
161 }
162 }
163
164 // Searching for destroyed unregistered actors.
165 for (const auto &actor_info: unregistered_actors) {
166 const ActorId &actor_id = actor_info.first;
167 if (current_actors.find(actor_id) == current_actors.end()
168 || registered_vehicles.Contains(actor_id)) {
169 deleted_unregistered.insert(actor_id);
170 }
171 }
172
173 return destroyed_actors;
174}
175
176void ALSM::UpdateRegisteredActorsData(const bool hybrid_physics_mode, ALSM::IdleInfo &max_idle_time) {
177
178 std::vector<ActorPtr> vehicle_list = registered_vehicles.GetList();
179 bool hero_actor_present = hero_actors.size() != 0u;
180 float physics_radius = parameters.GetHybridPhysicsRadius();
181 float physics_radius_square = SQUARE(physics_radius);
182 // A vehicle can die after the snapshot (destroyed through its handle, or by a map load): drop it, don't throw.
183 std::vector<ActorId> vanished_heroes;
184 std::vector<ActorId> vanished_vehicles;
185 // Update first the information regarding any hero vehicle.
186 for (auto &hero_actor_info: hero_actors){
187 try {
188 UpdateData(hybrid_physics_mode, hero_actor_info.second, hero_actor_present, physics_radius_square);
189 } catch (const std::exception &e) {
190 log_debug("Traffic Manager: dropping hero vehicle", hero_actor_info.first, ":", e.what());
191 vanished_heroes.push_back(hero_actor_info.first);
192 }
193 }
194 // Update information for all other registered vehicles.
195 for (const Actor &vehicle : vehicle_list) {
196 ActorId actor_id = vehicle->GetId();
197 if (hero_actors.find(actor_id) == hero_actors.end()) {
198 try {
199 UpdateData(hybrid_physics_mode, vehicle, hero_actor_present, physics_radius_square);
200 } catch (const std::exception &e) {
201 log_debug("Traffic Manager: dropping vehicle", actor_id, ":", e.what());
202 vanished_vehicles.push_back(actor_id);
203 continue;
204 }
205 UpdateIdleTime(max_idle_time, actor_id);
206 }
207 }
208 for (const ActorId actor_id : vanished_heroes) {
209 RemoveActor(actor_id, false);
210 }
211 for (const ActorId actor_id : vanished_vehicles) {
212 RemoveActor(actor_id, true);
213 }
214}
215
216void ALSM::UpdateData(const bool hybrid_physics_mode, const Actor &vehicle,
217 const bool hero_actor_present, const float physics_radius_square) {
218
219 ActorId actor_id = vehicle->GetId();
220 cg::Transform vehicle_transform = vehicle->GetTransform();
221 cg::Location vehicle_location = vehicle_transform.location;
222 cg::Rotation vehicle_rotation = vehicle_transform.rotation;
223 cg::Vector3D vehicle_velocity = vehicle->GetVelocity();
224 bool state_entry_present = simulation_state.ContainsActor(actor_id);
225
226 // Initializing idle times.
227 if (idle_time.find(actor_id) == idle_time.end() && current_timestamp.elapsed_seconds != 0.0) {
228 idle_time.insert({actor_id, current_timestamp.elapsed_seconds});
229 }
230
231 // Check if current actor is in range of hero actor and enable physics in hybrid mode.
232 bool in_range_of_hero_actor = false;
233 if (hero_actor_present && hybrid_physics_mode) {
234 for (auto &hero_actor_info: hero_actors) {
235 const ActorId &hero_actor_id = hero_actor_info.first;
236 if (simulation_state.ContainsActor(hero_actor_id)) {
237 const cg::Location &hero_location = simulation_state.GetLocation(hero_actor_id);
238 if (cg::Math::DistanceSquared(vehicle_location, hero_location) < physics_radius_square) {
239 in_range_of_hero_actor = true;
240 break;
241 }
242 }
243 }
244 }
245
246 bool enable_physics = hybrid_physics_mode ? in_range_of_hero_actor : true;
247 if (!has_physics_enabled.count(actor_id) || has_physics_enabled[actor_id] != enable_physics) {
248 if (hero_actors.find(actor_id) == hero_actors.end()) {
249 vehicle->SetSimulatePhysics(enable_physics);
250 has_physics_enabled[actor_id] = enable_physics;
251 if (enable_physics == true && state_entry_present) {
252 vehicle->SetTargetVelocity(simulation_state.GetVelocity(actor_id));
253 }
254 }
255 }
256
257 // If physics are disabled, calculate velocity based on change in position.
258 // Do not use 'enable_physics' as turning off the physics in this tick doesn't remove the velocity.
259 // To avoid issues with other clients teleporting the actors, use the previous outpout location.
260 if (state_entry_present && !simulation_state.IsPhysicsEnabled(actor_id)){
261 cg::Location previous_location = simulation_state.GetLocation(actor_id);
262 cg::Location previous_end_location = simulation_state.GetHybridEndLocation(actor_id);
263 cg::Vector3D displacement = (previous_end_location - previous_location);
264 vehicle_velocity = displacement * INV_HYBRID_DT;
265 }
266
267 // Updated kinematic state object.
268 auto vehicle_ptr = std::static_pointer_cast<cc::Vehicle>(vehicle);
269 KinematicState kinematic_state{vehicle_location, vehicle_rotation,
270 vehicle_velocity, vehicle_ptr->GetSpeedLimit(),
271 enable_physics, cg::Location()};
272
273 // Updated traffic light state object.
274 TrafficLightState tl_state = {vehicle_ptr->GetTrafficLightState(), vehicle_ptr->IsAtTrafficLight()};
275
276 // Update simulation state.
277 if (state_entry_present) {
278 simulation_state.UpdateKinematicState(actor_id, kinematic_state);
279 simulation_state.UpdateTrafficLightState(actor_id, tl_state);
280 }
281 else {
282 cg::Vector3D dimensions = vehicle_ptr->GetBoundingBox().extent;
283 StaticAttributes attributes{ActorType::Vehicle, dimensions.x, dimensions.y, dimensions.z};
284
285 // One-time query of the physical steering lock: the motion-plan stage
286 // normalizes steering authority (gains and envelope) by it. Guarded so a
287 // failed RPC (e.g. the actor died this frame) falls back to the default.
288 try {
289 const auto physics_control = vehicle_ptr->GetPhysicsControl();
290 float max_steer_angle = 0.0f;
291 for (const auto &wheel : physics_control.wheels) {
292 max_steer_angle = std::max(max_steer_angle, wheel.max_steer_angle);
293 }
294 if (max_steer_angle > 1.0f) {
295 attributes.max_steer_angle = max_steer_angle;
296 }
297 } catch (const std::exception &) {}
298
299 simulation_state.AddActor(actor_id, kinematic_state, attributes, tl_state);
300 }
301}
302
303
305 for (auto &actor_info: unregistered_actors) {
306
307 const ActorId actor_id = actor_info.first;
308 const ActorPtr actor_ptr = actor_info.second;
309 const std::string type_id = actor_ptr->GetTypeId();
310
311 const cg::Transform actor_transform = actor_ptr->GetTransform();
312 const cg::Location actor_location = actor_transform.location;
313 const cg::Rotation actor_rotation = actor_transform.rotation;
314 const cg::Vector3D actor_velocity = actor_ptr->GetVelocity();
315 KinematicState kinematic_state {actor_location, actor_rotation, actor_velocity, -1.0f, true, cg::Location()};
316
317 TrafficLightState tl_state;
318 ActorType actor_type = ActorType::Any;
319 cg::Vector3D dimensions;
320 std::vector<SimpleWaypointPtr> nearest_waypoints;
321
322 bool state_entry_not_present = !simulation_state.ContainsActor(actor_id);
323 if (type_id.front() == 'v') {
324 auto vehicle_ptr = std::static_pointer_cast<cc::Vehicle>(actor_ptr);
325 kinematic_state.speed_limit = vehicle_ptr->GetSpeedLimit();
326
327 tl_state = {vehicle_ptr->GetTrafficLightState(), vehicle_ptr->IsAtTrafficLight()};
328
329 if (state_entry_not_present) {
330 dimensions = vehicle_ptr->GetBoundingBox().extent;
331 actor_type = ActorType::Vehicle;
332 StaticAttributes attributes {actor_type, dimensions.x, dimensions.y, dimensions.z};
333
334 simulation_state.AddActor(actor_id, kinematic_state, attributes, tl_state);
335 } else {
336 simulation_state.UpdateKinematicState(actor_id, kinematic_state);
337 simulation_state.UpdateTrafficLightState(actor_id, tl_state);
338 }
339
340 // Identify occupied waypoints.
341 cg::Vector3D extent = vehicle_ptr->GetBoundingBox().extent;
342 cg::Vector3D heading_vector = vehicle_ptr->GetTransform().GetForwardVector();
343 std::vector<cg::Location> corners = {actor_location + cg::Location(extent.x * heading_vector),
344 actor_location,
345 actor_location + cg::Location(-extent.x * heading_vector)};
346 for (cg::Location &vertex: corners) {
347 SimpleWaypointPtr nearest_waypoint = local_map->GetWaypoint(vertex);
348 if (nearest_waypoint != nullptr) {
349 nearest_waypoints.push_back(nearest_waypoint);
350 }
351 }
352 }
353 else if (type_id.front() == 'w') {
354 auto walker_ptr = std::static_pointer_cast<cc::Walker>(actor_ptr);
355
356 if (state_entry_not_present) {
357 dimensions = walker_ptr->GetBoundingBox().extent;
358 actor_type = ActorType::Pedestrian;
359 StaticAttributes attributes {actor_type, dimensions.x, dimensions.y, dimensions.z};
360
361 simulation_state.AddActor(actor_id, kinematic_state, attributes, tl_state);
362 } else {
363 simulation_state.UpdateKinematicState(actor_id, kinematic_state);
364 }
365
366 // Identify occupied waypoints.
367 SimpleWaypointPtr nearest_waypoint = local_map->GetWaypoint(actor_location);
368 if (nearest_waypoint != nullptr) {
369 nearest_waypoints.push_back(nearest_waypoint);
370 }
371 }
372
373 track_traffic.UpdateUnregisteredGridPosition(actor_id, nearest_waypoints);
374 }
375}
376
377void ALSM::UpdateIdleTime(std::pair<ActorId, double>& max_idle_time, const ActorId& actor_id) {
378 if (idle_time.find(actor_id) != idle_time.end()) {
379 double &idle_duration = idle_time.at(actor_id);
380 if (simulation_state.GetVelocity(actor_id).SquaredLength() > SQUARE(STOPPED_VELOCITY_THRESHOLD)) {
381 idle_duration = current_timestamp.elapsed_seconds;
382 }
383
384 // Checking maximum idle time.
385 if (max_idle_time.first == 0u || max_idle_time.second > idle_duration) {
386 max_idle_time = std::make_pair(actor_id, idle_duration);
387 }
388 }
389}
390
391bool ALSM::IsVehicleStuck(const ActorId& actor_id) {
392 if (idle_time.find(actor_id) != idle_time.end()) {
393 double delta_idle_time = current_timestamp.elapsed_seconds - idle_time.at(actor_id);
394 TrafficLightState tl_state = simulation_state.GetTLS(actor_id);
395 if ((delta_idle_time >= RED_TL_BLOCKED_TIME_THRESHOLD)
396 || (delta_idle_time >= BLOCKED_TIME_THRESHOLD && tl_state.tl_state != TLS::Red))
397 {
398 return true;
399 }
400 }
401 return false;
402}
403
404void ALSM::AddActor(const Actor actor) {
405 const ActorId actor_id = actor->GetId();
406 for (auto &&attribute : actor->GetAttributes()) {
407 if (attribute.GetId() != "base_type") {
408 continue;
409 }
410 std::string value = attribute.GetValue();
411 std::transform(
412 value.begin(),
413 value.end(),
414 value.begin(),
415 [](unsigned char c) { return std::tolower(c); });
416 const std::string_view value_view{value};
417 const auto match = std::find(
418 large_vehicle_types.begin(),
420 value_view);
421 if (match != large_vehicle_types.end()) {
422 large_vehicles[actor_id] = std::make_pair(0.0f, false);
423 }
424 // There is at most one "base_type" attribute, so stop scanning once it
425 // has been handled.
426 break;
427 }
428}
429
430void ALSM::RemoveActor(const ActorId actor_id, const bool registered_actor) {
431 if (registered_actor) {
432 registered_vehicles.Remove({actor_id});
433 buffer_map.erase(actor_id);
434 idle_time.erase(actor_id);
440
441 large_vehicles.erase(actor_id);
442 }
443 else {
444 unregistered_actors.erase(actor_id);
445 hero_actors.erase(actor_id);
446 }
447
448 track_traffic.DeleteActor(actor_id);
450}
451
453 unregistered_actors.clear();
454 idle_time.clear();
455 hero_actors.clear();
457 current_timestamp = world.GetSnapshot().GetTimestamp();
458}
459
460} // namespace traffic_manager
461} // namespace carla
#define SQUARE(a)
This file contains various constants used in traffic manager arranged into sensible namespaces for re...
Definition Constants.h:14
static constexpr auto DistanceSquared(const Vector3D &a, const Vector3D &b)
Definition Math.h:70
Euler angles of a rotation in CARLA's / Unreal's left-handed frame: x forward, y right,...
Definition Rotation.h:45
A rigid transform in CARLA's / Unreal's left-handed frame: x forward, y right, z up,...
void AddActor(const Actor actor)
Definition ALSM.cpp:404
const cc::World & world
Definition ALSM.h:58
void IdentifyNewActors(const ActorList &actor_list)
Definition ALSM.cpp:122
void RemoveActor(const ActorId actor_id, const bool registered_actor)
Definition ALSM.cpp:430
AtomicActorSet & registered_vehicles
Definition ALSM.h:46
static constexpr std::array< std::string_view, 2 > large_vehicle_types
Definition ALSM.h:72
std::unordered_map< ActorId, std::pair< float, bool > > & large_vehicles
Definition ALSM.h:70
LocalizationStage & localization_stage
Definition ALSM.h:61
const LocalMapPtr & local_map
Definition ALSM.h:59
std::unordered_map< ActorId, bool > has_physics_enabled
Definition ALSM.h:69
VehicleLightStage & vehicle_light_stage
Definition ALSM.h:65
std::pair< ActorId, double > IdleInfo
Definition ALSM.h:88
bool IsVehicleStuck(const ActorId &actor_id)
Definition ALSM.cpp:391
MotionPlanStage & motion_plan_stage
Definition ALSM.h:64
IdleTimeMap idle_time
Definition ALSM.h:51
std::pair< ActorIdSet, ActorIdSet > DestroyeddActors
Definition ALSM.h:83
CollisionStage & collision_stage
Definition ALSM.h:62
void UpdateData(const bool hybrid_physics_mode, const Actor &vehicle, const bool hero_actor_present, const float physics_radius_square)
Definition ALSM.cpp:216
ActorMap unregistered_actors
Definition ALSM.h:48
cc::Timestamp current_timestamp
Definition ALSM.h:68
const Parameters & parameters
Definition ALSM.h:57
std::vector< ActorId > & marked_for_removal
Definition ALSM.h:56
SimulationState & simulation_state
Definition ALSM.h:60
void UpdateRegisteredActorsData(const bool hybrid_physics_mode, IdleInfo &max_idle_time)
Definition ALSM.cpp:176
BufferMap & buffer_map
Definition ALSM.h:49
ALSM(AtomicActorSet &registered_vehicles, BufferMap &buffer_map, TrackTraffic &track_traffic, std::vector< ActorId > &marked_for_removal, const Parameters &parameters, const cc::World &world, const LocalMapPtr &local_map, SimulationState &simulation_state, std::unordered_map< ActorId, std::pair< float, bool > > &large_vehicles, LocalizationStage &localization_stage, CollisionStage &collision_stage, TrafficLightStage &traffic_light_stage, MotionPlanStage &motion_plan_stage, VehicleLightStage &vehicle_light_stage)
Definition ALSM.cpp:22
TrafficLightStage & traffic_light_stage
Definition ALSM.h:63
void UpdateIdleTime(std::pair< ActorId, double > &max_idle_time, const ActorId &actor_id)
Definition ALSM.cpp:377
TrackTraffic & track_traffic
Definition ALSM.h:54
DestroyeddActors IdentifyDestroyedActors(const ActorList &actor_list)
Definition ALSM.cpp:144
double elapsed_last_actor_destruction
Definition ALSM.h:67
void Remove(std::vector< ActorId > actor_id_list)
std::vector< ActorPtr > GetList()
This class has functionality to detect potential collision with a nearby actor.
void RemoveActor(const ActorId actor_id) override
This class has functionality to maintain a horizon of waypoints ahead of the vehicle for it to follow...
void RemoveActor(const ActorId actor_id) override
void RemoveActor(const ActorId actor_id)
bool GetOSMMode() const
Method to get Open Street Map mode.
float GetHybridPhysicsRadius() const
Method to retrieve hybrid physics radius.
bool GetHybridPhysicsMode() const
Method to retrieve hybrid physics mode.
This class holds the state of all the vehicles in the simlation.
bool ContainsActor(ActorId actor_id) const
cg::Location GetLocation(const ActorId actor_id) const
cg::Location GetHybridEndLocation(const ActorId actor_id) const
void UpdateKinematicState(ActorId actor_id, KinematicState state)
void AddActor(ActorId actor_id, KinematicState kinematic_state, StaticAttributes attributes, TrafficLightState tl_state)
void UpdateTrafficLightState(ActorId actor_id, TrafficLightState state)
cg::Vector3D GetVelocity(const ActorId actor_id) const
bool IsPhysicsEnabled(const ActorId actor_id) const
TrafficLightState GetTLS(const ActorId actor_id) const
void UpdateUnregisteredGridPosition(const ActorId actor_id, const std::vector< SimpleWaypointPtr > waypoints)
void DeleteActor(ActorId actor_id)
Method to delete actor data from tracking.
This class has functionality for responding to traffic lights and managing entry into non-signalized ...
void RemoveActor(const ActorId actor_id) override
This class has functionality for turning on/off the vehicle lights according to the current vehicle s...
void RemoveActor(const ActorId actor_id) override
carla::SharedPtr< cc::Actor > ActorPtr
carla::SharedPtr< cc::Actor > Actor
carla::SharedPtr< cc::ActorList > ActorList
Definition ALSM.h:35
std::shared_ptr< InMemoryMap > LocalMapPtr
Definition ALSM.h:38
std::shared_ptr< SimpleWaypoint > SimpleWaypointPtr
std::unordered_set< ActorId > ActorIdSet
std::unordered_map< carla::ActorId, Buffer > BufferMap
This file contains definitions of common data structures used in traffic manager.
constexpr float SquaredLength() const