CARLA
Loading...
Searching...
No Matches
MotionPlanStage.cpp
Go to the documentation of this file.
1// Copyright (c) 2026 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#include <algorithm>
8#include <cmath>
9#include <limits>
10
14
18
20
21namespace carla {
22namespace traffic_manager {
23
24using namespace constants::MotionPlan;
25using namespace constants::WaypointSelection;
26using namespace constants::SpeedThreshold;
27
28using constants::HybridMode::HYBRID_MODE_DT;
29using constants::HybridMode::HYBRID_MODE_DT_FL;
30using constants::PID::DT;
31using constants::Collision::EPSILON;
32
66
67void MotionPlanStage::SetCycleTimestamp(const cc::Timestamp &timestamp) {
68 current_timestamp = timestamp;
69}
70
71void MotionPlanStage::Update(const unsigned long index) {
72 const ActorId actor_id = vehicle_id_list.at(index);
73 const cg::Location vehicle_location = simulation_state.GetLocation(actor_id);
74 const cg::Vector3D vehicle_velocity = simulation_state.GetVelocity(actor_id);
75 const cg::Rotation vehicle_rotation = simulation_state.GetRotation(actor_id);
76 const float vehicle_speed = vehicle_velocity.Length();
77 const cg::Vector3D vehicle_heading = simulation_state.GetHeading(actor_id);
78 const bool vehicle_physics_enabled = simulation_state.IsPhysicsEnabled(actor_id);
79 const float vehicle_speed_limit = simulation_state.GetSpeedLimit(actor_id);
80 const Buffer &waypoint_buffer = buffer_map.at(actor_id);
81 const LocalizationData &localization = localization_frame.at(index);
82 const CollisionHazardData &collision_hazard = collision_frame.at(index);
83 const bool &tl_hazard = tl_frame.at(index);
84 StateEntry current_state;
85
86 // Instanciating teleportation transform as current vehicle transform.
87 cg::Transform teleportation_transform = cg::Transform(vehicle_location, vehicle_rotation);
88
89 // Target velocity for vehicle.
90 float max_target_velocity = parameters.GetVehicleTargetVelocity(actor_id, vehicle_speed_limit) / 3.6f;
91
92 // Algorithm to reduce speed near landmarks
93 float max_landmark_target_velocity = GetLandmarkTargetVelocity(*(waypoint_buffer.at(0)), vehicle_location, actor_id, max_target_velocity);
94
95 // Algorithm to reduce speed near turns
96 float max_turn_target_velocity = GetTurnTargetVelocity(waypoint_buffer, vehicle_location, max_target_velocity);
97 max_target_velocity = std::min(std::min(max_target_velocity, max_landmark_target_velocity), max_turn_target_velocity);
98
99 // Collision handling and target velocity correction.
100 std::pair<bool, float> collision_response = CollisionHandling(collision_hazard, tl_hazard, vehicle_velocity,
101 vehicle_heading, max_target_velocity);
102 bool collision_emergency_stop = collision_response.first;
103 float dynamic_target_velocity = collision_response.second;
104
105 // Don't enter junction if there isn't enough free space after the junction.
106 bool safe_after_junction = SafeAfterJunction(localization, tl_hazard, collision_emergency_stop);
107
108 // In case of collision or traffic light hazard.
109 bool emergency_stop = tl_hazard || collision_emergency_stop || !safe_after_junction;
110
111 if (vehicle_physics_enabled) {
112 ActuationSignal actuation_signal{0.0f, 0.0f, 0.0f};
113
114 // Vehicle steering geometry. See constants::PID: the pursuit law and
115 // the steering-authority normalization below are computed from the
116 // vehicle's own wheelbase (approximated from the bounding-box length)
117 // and physical wheel lock instead of the car-class anchor.
118 const float vehicle_length{2.0f * simulation_state.GetDimensions(actor_id).x};
119 const float wheel_lock{std::max(simulation_state.GetMaxSteerAngle(actor_id), 1.0f)};
120 const float wheelbase{constants::PID::WHEELBASE_FRACTION * vehicle_length};
121
122 // The pursuit reference is the actor origin (bounding-box centre).
123 // Kinematically pure pursuit is exact at the rear axle, but for lane
124 // containment of a rigid body the centre is the optimal reference (the
125 // body then splits its wheelbase chord evenly across the lane), and a
126 // rear-axle reference was measured to add enough loop delay on long
127 // vehicles to weave through tight junction turns.
128 const cg::Location &pursuit_reference{vehicle_location};
129
130 // Resolve the target waypoint by interpolating along the buffer at
131 // target_point_distance ahead of the reference.
132 float target_point_distance{std::clamp(
133 vehicle_speed * TARGET_WAYPOINT_TIME_HORIZON,
134 MIN_TARGET_WAYPOINT_DISTANCE,
135 MAX_TARGET_WAYPOINT_DISTANCE)};
136 auto target_data = GetTargetData(
137 waypoint_buffer,
138 target_point_distance,
139 pursuit_reference);
140
141 // Curvature-aware pursuit-distance cap. Pursuing a point d ahead tracks
142 // the chord of the path, which cuts a curve of radius R by the sagitta
143 // ~d^2/(8R): through junction turns (R ~ 11 m on Town10) the vehicle
144 // turns in before the lane does and sweeps ~1.4 m into the adjacent
145 // lane. Bound d so the geometric cut stays below
146 // MAX_PURSUIT_CHORD_SAGITTA; straight paths (R -> inf) are unaffected.
147 const auto mid_data = GetTargetData(
148 waypoint_buffer,
149 0.5f * target_point_distance,
150 pursuit_reference);
151 const float local_radius = GetThreePointCircleRadius(
152 waypoint_buffer.front()->GetLocation(),
153 mid_data.first,
154 target_data.first);
155 const float sagitta_distance_cap =
156 std::sqrt(8.0f * local_radius * MAX_PURSUIT_CHORD_SAGITTA);
157 if (sagitta_distance_cap < target_point_distance) {
158 target_point_distance = std::max(sagitta_distance_cap,
159 MIN_TARGET_WAYPOINT_DISTANCE);
160 target_data = GetTargetData(
161 waypoint_buffer,
162 target_point_distance,
163 pursuit_reference);
164 }
165 const uint64_t target_index = target_data.second;
166 cg::Location target_location{target_data.first};
167 const SimpleWaypointPtr target_waypoint = waypoint_buffer.at(target_index);
168
169 // The lateral PID linearizes the pure-pursuit law, whose equivalent
170 // proportional gain is inversely proportional to the pursuit distance
171 // (kappa = 2 * sin(alpha) / d). The gains are tuned at the cruise
172 // anchor d = MAX_TARGET_WAYPOINT_DISTANCE; when the target sits closer
173 // (low speed, or the curvature cap above) the loop gain must scale by
174 // d_ref / d or the controller winds on steering too slowly for the
175 // path curvature and runs wide through junction turns.
176 const float lateral_gain_scale =
177 MAX_TARGET_WAYPOINT_DISTANCE / std::max(target_point_distance, 1.0f);
178
179 // Steering-authority normalization: normalized steer maps to curvature
180 // as kappa = tan(steer * max_steer_angle) / wheelbase, so long vehicles
181 // produce proportionally less curvature per command than the car-class
182 // fleet the gains and the STEER_LIMIT_GAIN envelope are anchored on.
183 // The STEER_LIMIT_GAIN envelope is a physical curvature guard, so it
184 // scales with the vehicle's authority. See constants::PID.
185 const float steer_authority_correction{std::clamp(
186 (vehicle_length / constants::PID::REF_VEHICLE_LENGTH) *
187 (constants::PID::REF_MAX_STEER_ANGLE / wheel_lock),
188 1.0f, constants::PID::MAX_STEER_AUTHORITY_CORRECTION)};
189
190 float base_offset{CalculateBaseOffset(
191 actor_id,
192 waypoint_buffer,
193 target_waypoint->CheckJunction(),
194 target_index)};
195 const auto right_vector = target_waypoint->GetTransform().GetRightVector();
196
197 // Suppress the wide-turn swing when the side it would move into is
198 // occupied by a nearby vehicle (parked, stopped or adjacent traffic).
199 if (std::abs(base_offset) > EPSILON) {
200 const cg::Vector3D offset_direction{
201 (base_offset > 0.0f) ? right_vector : (-1.0f * right_vector)};
202 if (IsWideTurnSideOccupied(actor_id, offset_direction, std::abs(base_offset))) {
203 base_offset = 0.0f;
204 }
205 }
206
207 const float offset{parameters.GetLaneOffset(actor_id) + base_offset};
208 const auto offset_location = cg::Location(cg::Vector3D(
209 offset * right_vector.x,
210 offset * right_vector.y,
211 0.0f));
212 target_location = target_location + offset_location;
213
214 // Compute the angular deviation directly as the angle between the
215 // vehicle heading and the target direction. atan2(0, 0) is
216 // well-defined and returns 0 when the reference and target locations
217 // coincide on the very first tick before any displacement.
218 const cg::Vector3D target_vector{target_location - pursuit_reference};
219 const float target_yaw{std::atan2(target_vector.y, target_vector.x) * 180.0f / PI};
220 float angular_deviation{target_yaw - vehicle_rotation.yaw};
221 if (angular_deviation > 180.0f) {
222 angular_deviation -= 360.0f;
223 } else if (angular_deviation < -180.0f) {
224 angular_deviation += 360.0f;
225 }
226 angular_deviation /= 180.0f; // Normalised to [-1, 1].
227
228 // Full throttle with saturated steering produces accelerating donuts
229 // when the target sits far off-heading (after a spin, a collision or
230 // a wrong-way resume). Cap the target speed while grossly misaligned
231 // so full-lock turns stay tight; speed resumes as heading converges.
232 if (std::abs(angular_deviation) > 0.25f) { // > 45 degrees
233 dynamic_target_velocity = std::min(dynamic_target_velocity, 3.0f);
234 }
235 // --- Stuck / misaligned vehicle recovery (K-turn) -----------------
236 // Two situations the forward PID cannot solve: a vehicle commanded to
237 // move (no red light, no vehicle ahead) that stays immobile is wedged
238 // against something and would grind at full lock forever; a vehicle
239 // whose target sits far off-heading (spun by a collision, player
240 // driving, wrong-way resume) would chase a target behind itself in
241 // full-lock circles. Both run a K-turn: alternate reverse and forward
242 // phases with full steering toward the target until roughly aligned,
243 // then resume the PID with a fresh state.
244 {
245 using namespace constants::StuckRecovery;
246 const double now = current_timestamp.elapsed_seconds;
247 const float abs_deviation = std::abs(angular_deviation);
248 bool recovering = false;
249 auto rec_it = recovery_state.find(actor_id);
250 if (rec_it != recovery_state.end()) {
251 if (abs_deviation < ALIGN_EXIT_DEVIATION) {
252 recovery_state.erase(rec_it);
253 stuck_since.erase(actor_id);
254 // Seed the fresh PID state with the current deviation: a zeroed
255 // previous deviation would make the first post-recovery tick see
256 // the full residual error as a one-tick change and kick the
257 // derivative term into a saturated steer, restarting the swing
258 // the K-turn just corrected.
259 pid_state_map[actor_id] = StateEntry{current_timestamp, angular_deviation, 0.0f, 0.0f};
260 } else {
261 recovering = true;
262 if (now >= rec_it->second.phase_until) {
263 rec_it->second.reversing = !rec_it->second.reversing;
264 rec_it->second.phase_until = now + PHASE_DURATION;
265 }
266 // Refresh the latched direction only once the deviation sign is
267 // unambiguous (target no longer near dead-astern).
268 if (abs_deviation < 0.5f) {
269 rec_it->second.steer_direction =
270 (angular_deviation > 0.0f) ? 1.0f : -1.0f;
271 }
272 }
273 }
274 if (!recovering && !emergency_stop) {
275 bool stuck_trigger = false;
276 if (dynamic_target_velocity > STUCK_SPEED && vehicle_speed < STUCK_SPEED) {
277 auto stuck_it = stuck_since.insert({actor_id, now}).first;
278 stuck_trigger = (now - stuck_it->second > STUCK_TIME);
279 } else {
280 stuck_since.erase(actor_id);
281 }
282 const bool misaligned = abs_deviation > ALIGN_ENTER_DEVIATION &&
283 vehicle_speed < MISALIGN_MAX_SPEED;
284 if (stuck_trigger || misaligned) {
285 recovery_state[actor_id] = RecoveryState{
286 now + PHASE_DURATION, true,
287 (angular_deviation > 0.0f) ? 1.0f : -1.0f};
288 recovering = true;
289 }
290 }
291 if (recovering) {
292 const RecoveryState &rs = recovery_state.at(actor_id);
293 carla::rpc::VehicleControl recovery_control;
294 recovery_control.reverse = rs.reversing;
295 recovery_control.throttle = rs.reversing ? REVERSE_THROTTLE : FORWARD_THROTTLE;
296 recovery_control.brake = 0.0f;
297 recovery_control.steer =
298 (rs.reversing ? -rs.steer_direction : rs.steer_direction) * RECOVERY_STEER;
299 output_array.at(index) = carla::rpc::Command::ApplyVehicleControl(actor_id, recovery_control);
300 return;
301 }
302 }
303
304 // If previous state for vehicle not found, initialize state entry.
305 if (pid_state_map.find(actor_id) == pid_state_map.end()) {
306 const auto initial_state = StateEntry{current_timestamp, 0.0f, 0.0f, 0.0f};
307 pid_state_map.insert({actor_id, initial_state});
308 }
309
310 // Retrieving the previous state.
311 traffic_manager::StateEntry previous_state;
312 previous_state = pid_state_map.at(actor_id);
313
314 // Select PID parameters.
315 std::vector<float> longitudinal_parameters;
316 std::vector<float> lateral_parameters;
317 if (vehicle_speed > HIGHWAY_SPEED) {
318 longitudinal_parameters = highway_longitudinal_parameters;
319 lateral_parameters = highway_lateral_parameters;
320 } else {
321 longitudinal_parameters = urban_longitudinal_parameters;
322 lateral_parameters = urban_lateral_parameters;
323 }
324
325 // Measured controller period in simulation time. In synchronous mode
326 // this is fixed_delta_seconds; in asynchronous mode it is one server
327 // frame, which under render load can stretch well past the nominal DT
328 // the gains were tuned at -- RunStep compensates. Non-positive values
329 // (first tick after registration or a recovery reseed, where previous
330 // and current share a timestamp) fall back to the nominal period.
331 float control_dt = static_cast<float>(
332 current_timestamp.elapsed_seconds - previous_state.time_instance.elapsed_seconds);
333 if (control_dt <= 0.0f) {
334 control_dt = DT;
335 }
336
337 const float reference_velocity{PID::ShapeReferenceVelocity(
338 previous_state.reference_velocity,
339 vehicle_speed,
340 dynamic_target_velocity,
341 control_dt,
342 emergency_stop)};
343 const float velocity_deviation{PID::RelativeVelocityDeviation(
344 reference_velocity, vehicle_speed, dynamic_target_velocity)};
345
346 // If physics is enabled for the vehicle, use PID controller.
347 // State update for vehicle.
348 current_state = {current_timestamp, angular_deviation, velocity_deviation, 0.0f};
349 current_state.reference_velocity = reference_velocity;
350
351 // Geometric pure-pursuit lateral command. The previous linearized
352 // proportional term (P * deviation) was tuned at car-scale commands
353 // (|steer| ~ 0.1) and over-curves long vehicles, which need
354 // |steer| ~ 0.4-0.5 through junction turns where tan(steer * lock) is
355 // well past its linear range (measured: trucks settling ~1 m inside
356 // their reference). Commanding the pure-pursuit curvature
357 // kappa = margin * 2 sin(alpha) / d and inverting the vehicle's own
358 // steering map atan(wheelbase * kappa) / lock is exact for every
359 // geometry, and reduces to the validated P = 2 linear gain for the
360 // anchor car at the cruise pursuit distance (see Constants.h).
361 const float wheel_lock_rad{wheel_lock * PI / 180.0f};
362 const float alpha_rad{angular_deviation * PI};
363 const float pursuit_curvature{constants::PID::PURSUIT_CURVATURE_MARGIN *
364 2.0f * std::sin(alpha_rad) /
365 std::max(target_point_distance, 1.0f)};
366 const float pursuit_steer{std::atan(wheelbase * pursuit_curvature) /
367 wheel_lock_rad};
368
369 // Damping (derivative) scale: pursuit-distance schedule x authority,
370 // capped at the ceiling the schedule alone reaches on the tuned fleet.
371 const float lateral_damping_scale{std::min(
372 lateral_gain_scale * steer_authority_correction,
373 constants::PID::MAX_LATERAL_GAIN_SCALE)};
374
375 // Controller actuation.
376 actuation_signal = PID::RunStep(current_state, previous_state,
377 longitudinal_parameters, lateral_parameters,
378 vehicle_speed, control_dt,
379 pursuit_steer,
380 lateral_damping_scale,
381 steer_authority_correction);
382
383 if (emergency_stop) {
384 actuation_signal.throttle = 0.0f;
385 actuation_signal.brake = 1.0f;
386 } else {
387 PID::SmoothActuation(previous_state, control_dt, vehicle_speed, actuation_signal);
388 }
389
390 // Constructing the actuation signal.
391 carla::rpc::VehicleControl vehicle_control;
392 vehicle_control.throttle = actuation_signal.throttle;
393 vehicle_control.brake = actuation_signal.brake;
394 vehicle_control.steer = actuation_signal.steer;
395
396 output_array.at(index) = carla::rpc::Command::ApplyVehicleControl(actor_id, vehicle_control);
397
398 // Updating PID state.
399 current_state.steer = actuation_signal.steer;
400 current_state.throttle = actuation_signal.throttle;
401 current_state.brake = actuation_signal.brake;
402 StateEntry &state = pid_state_map.at(actor_id);
403 state = current_state;
404 }
405 // For physics-less vehicles, determine position and orientation for teleportation.
406 else {
407 // Flushing controller state for vehicle.
408 current_state = {current_timestamp,
409 0.0f, 0.0f,
410 0.0f};
411
412 // Add entry to teleportation duration clock table if not present.
413 if (teleportation_instance.find(actor_id) == teleportation_instance.end()) {
414 teleportation_instance.insert({actor_id, current_timestamp});
415 }
416
417 // Measuring time elapsed since last teleportation for the vehicle.
418 double elapsed_time = current_timestamp.elapsed_seconds - teleportation_instance.at(actor_id).elapsed_seconds;
419
420 // Find a location ahead of the vehicle for teleportation to achieve intended velocity.
421 if (!emergency_stop && (parameters.GetSynchronousMode() || elapsed_time > HYBRID_MODE_DT)) {
422
423 // Target displacement magnitude to achieve target velocity.
424 const float target_displacement = dynamic_target_velocity * HYBRID_MODE_DT_FL;
425 SimpleWaypointPtr teleport_target = waypoint_buffer.front();
426 cg::Transform target_base_transform = teleport_target->GetTransform();
427 cg::Location target_base_location = target_base_transform.location;
428 cg::Vector3D target_heading = target_base_transform.GetForwardVector();
429 cg::Vector3D correct_heading = (target_base_location - vehicle_location).MakeUnitVector(EPSILON);
430
431 if (vehicle_location.Distance(target_base_location) < target_displacement) {
432 cg::Location teleportation_location = vehicle_location + cg::Location(target_heading.MakeUnitVector(EPSILON) * target_displacement);
433 teleportation_transform = cg::Transform(teleportation_location, target_base_transform.rotation);
434 }
435 else {
436 cg::Location teleportation_location = vehicle_location + cg::Location(correct_heading * target_displacement);
437 teleportation_transform = cg::Transform(teleportation_location, target_base_transform.rotation);
438 }
439 // In case of an emergency stop, stay in the same location.
440 // Also, teleport only once every dt in asynchronous mode.
441 } else {
442 teleportation_transform = cg::Transform(vehicle_location, simulation_state.GetRotation(actor_id));
443 }
444 // Constructing the actuation signal.
445 output_array.at(index) = carla::rpc::Command::ApplyTransform(actor_id, teleportation_transform);
446 simulation_state.UpdateKinematicHybridEndLocation(actor_id, teleportation_transform.location);
447 }
448}
449
451 const bool tl_hazard,
452 const bool collision_emergency_stop) {
453
454 SimpleWaypointPtr junction_end_point = localization.junction_end_point;
455 SimpleWaypointPtr safe_point = localization.safe_point;
456
457 bool safe_after_junction = true;
458 if (!tl_hazard && !collision_emergency_stop
459 && localization.is_at_junction_entrance
460 && junction_end_point != nullptr && safe_point != nullptr
461 && junction_end_point->DistanceSquared(safe_point) > SQUARE(MIN_SAFE_INTERVAL_LENGTH)) {
462
463 ActorIdSet passing_safe_point = track_traffic.GetPassingVehicles(safe_point->GetId());
464 ActorIdSet passing_junction_end_point = track_traffic.GetPassingVehicles(junction_end_point->GetId());
465 cg::Location mid_point = (junction_end_point->GetLocation() + safe_point->GetLocation())/2.0f;
466
467 // Only check for vehicles that have the safe point in their passing waypoint, but not
468 // the junction end point.
469 ActorIdSet difference;
470 std::set_difference(passing_safe_point.begin(), passing_safe_point.end(),
471 passing_junction_end_point.begin(), passing_junction_end_point.end(),
472 std::inserter(difference, difference.begin()));
473 if (difference.size() > 0) {
474 for (const ActorId &blocking_id: difference) {
475 cg::Location blocking_actor_location = simulation_state.GetLocation(blocking_id);
476 if (cg::Math::DistanceSquared(blocking_actor_location, mid_point) < SQUARE(MAX_JUNCTION_BLOCK_DISTANCE)
477 && simulation_state.GetVelocity(blocking_id).SquaredLength() < SQUARE(AFTER_JUNCTION_MIN_SPEED)) {
478 safe_after_junction = false;
479 break;
480 }
481 }
482 }
483 }
484
485 return safe_after_junction;
486}
487
489 const ActorId actor_id,
490 const Buffer &waypoint_buffer,
491 const bool is_target_junction,
492 const uint64_t target_index) {
493
494 // This offset is meant to make large vehicles do wider turns at intersections.
495 if (large_vehicles.find(actor_id) == large_vehicles.end() || !is_target_junction) {
496 return 0.0f;
497 }
498
499 // The wide-turn manoeuvre can be disabled per-vehicle or globally.
500 if (!parameters.GetLargeVehicleWideTurn(actor_id)) {
501 return 0.0f;
502 }
503
504 const auto &large_vehicle = large_vehicles.at(actor_id);
505
506 // Going straight at the intersection: no offset to apply.
507 if (large_vehicle.first == 0.0f) {
508 return 0.0f;
509 }
510
511 float junction_missing_length{0.0f};
512 for (unsigned long i = target_index; i < waypoint_buffer.size(); ++i) {
513 const SimpleWaypointPtr current_waypoint = waypoint_buffer.at(i);
514
515 if (i > target_index) {
516 const SimpleWaypointPtr prev_waypoint = waypoint_buffer.at(i - 1u);
517 const float new_distance = current_waypoint->Distance(prev_waypoint->GetLocation());
518 junction_missing_length += new_distance;
519 }
520
521 if (!current_waypoint->CheckJunction()) {
522 break;
523 }
524 }
525
526 const float junction_length{large_vehicle.first};
527 const bool turn_flag{large_vehicle.second};
528
529 // Scale the offset magnitude by the vehicle's actual length so a short bus
530 // and a long truck no longer share the same fixed displacement.
531 // GetDimensions returns half-extents, so the full length is twice the x extent.
532 const float vehicle_length{2.0f * simulation_state.GetDimensions(actor_id).x};
533 const float max_offset{LargeVehicleOffsetMagnitude(
534 vehicle_length,
535 LARGE_VEHICLES_JUNCTION_REF_LENGTH,
536 LARGE_VEHICLES_JUNCTION_OFFSET_GAIN,
537 LARGE_VEHICLES_JUNCTION_OFFSET)};
538
539 // Fraction of the junction still ahead of the target waypoint (1 at the
540 // entry, 0 at the exit). The profile opens the vehicle up at the entry and
541 // attenuates the inboard cut-in near the exit.
542 const float t{junction_missing_length / junction_length};
544 t,
545 max_offset,
546 LARGE_VEHICLES_JUNCTION_POINT,
547 LARGE_VEHICLES_JUNCTION_INBOARD_SCALE)};
548
549 // Sign depends on the turn direction (right vs. left).
550 offset = turn_flag ? offset : -offset;
551 return offset;
552}
553
555 const ActorId actor_id,
556 const cg::Vector3D offset_direction,
557 const float offset_magnitude) {
558
559 const ActorIdSet overlapping_vehicles{track_traffic.GetOverlappingVehicles(actor_id)};
560 if (overlapping_vehicles.empty()) {
561 return false;
562 }
563
564 std::vector<std::pair<cg::Location, float>> neighbours;
565 neighbours.reserve(overlapping_vehicles.size());
566 for (const ActorId other_id : overlapping_vehicles) {
567 if (other_id == actor_id) {
568 continue;
569 }
570 const cg::Vector3D other_dimensions{simulation_state.GetDimensions(other_id)};
571 const float radius{std::max(other_dimensions.x, other_dimensions.y)};
572 neighbours.emplace_back(simulation_state.GetLocation(other_id), radius);
573 }
574
575 const cg::Location ego_location{simulation_state.GetLocation(actor_id)};
576 const cg::Vector3D ego_forward{simulation_state.GetHeading(actor_id)};
577 const float longitudinal_window{
578 simulation_state.GetDimensions(actor_id).x + LARGE_VEHICLES_JUNCTION_SIDE_MARGIN};
579
581 ego_location,
582 ego_forward,
583 offset_direction,
584 offset_magnitude,
585 LARGE_VEHICLES_JUNCTION_CLEARANCE,
586 longitudinal_window,
587 neighbours);
588}
589
590std::pair<bool, float> MotionPlanStage::CollisionHandling(const CollisionHazardData &collision_hazard,
591 const bool tl_hazard,
592 const cg::Vector3D vehicle_velocity,
593 const cg::Vector3D vehicle_heading,
594 const float max_target_velocity) {
595 bool collision_emergency_stop = false;
596 float dynamic_target_velocity = max_target_velocity;
597 const float vehicle_speed = vehicle_velocity.Length();
598
599 if (collision_hazard.hazard && !tl_hazard) {
600 const ActorId other_actor_id = collision_hazard.hazard_actor_id;
601 const cg::Vector3D other_velocity = simulation_state.GetVelocity(other_actor_id);
602 const float vehicle_relative_speed = (vehicle_velocity - other_velocity).Length();
603 const float available_distance_margin = collision_hazard.available_distance_margin;
604
605 const float other_speed_along_heading = cg::Math::Dot(other_velocity, vehicle_heading);
606
607 // Consider collision avoidance decisions only if there is positive relative velocity
608 // of the ego vehicle (meaning, ego vehicle is closing the gap to the lead vehicle).
609 if (vehicle_relative_speed > EPSILON_RELATIVE_SPEED) {
610 // If other vehicle is approaching lead vehicle and lead vehicle is further
611 // than follow_lead_distance 0 kmph -> 5m, 100 kmph -> 10m.
612 float follow_lead_distance = FOLLOW_LEAD_FACTOR * vehicle_speed + MIN_FOLLOW_LEAD_DISTANCE;
613 if (available_distance_margin > follow_lead_distance) {
614 // Then reduce the gap between the vehicles till FOLLOW_LEAD_DISTANCE
615 // by maintaining a relative speed of other_speed_along_heading
616 dynamic_target_velocity = other_speed_along_heading;
617 }
618 // If vehicle is approaching a lead vehicle and the lead vehicle is further
619 // than CRITICAL_BRAKING_MARGIN but closer than FOLLOW_LEAD_DISTANCE.
620 else if (available_distance_margin > CRITICAL_BRAKING_MARGIN) {
621 // Then follow the lead vehicle by acquiring it's speed along current heading.
622 dynamic_target_velocity = std::max(other_speed_along_heading, RELATIVE_APPROACH_SPEED);
623 } else {
624 // If lead vehicle closer than CRITICAL_BRAKING_MARGIN, initiate emergency stop.
625 collision_emergency_stop = true;
626 }
627 }
628 if (available_distance_margin < CRITICAL_BRAKING_MARGIN) {
629 collision_emergency_stop = true;
630 }
631 }
632
633 float max_gradual_velocity = PERC_MAX_SLOWDOWN * vehicle_speed;
634 if (dynamic_target_velocity < vehicle_speed - max_gradual_velocity) {
635 // Don't slow more than PERC_MAX_SLOWDOWN per frame.
636 dynamic_target_velocity = vehicle_speed - max_gradual_velocity;
637 }
638 dynamic_target_velocity = std::min(max_target_velocity, dynamic_target_velocity);
639
640 return {collision_emergency_stop, dynamic_target_velocity};
641}
642
644 const cg::Location vehicle_location,
645 const ActorId actor_id,
646 float max_target_velocity) {
647
648 auto const max_distance = LANDMARK_DETECTION_TIME * max_target_velocity;
649
650 float landmark_target_velocity = std::numeric_limits<float>::max();
651
652 auto all_landmarks = waypoint.GetWaypoint()->GetAllLandmarksInDistance(max_distance, false);
653
654 for (auto &landmark: all_landmarks) {
655
656 auto landmark_location = landmark->GetWaypoint()->GetTransform().location;
657 auto landmark_type = landmark->GetType();
658 auto distance = landmark_location.Distance(vehicle_location);
659
660 if (distance > max_distance) {
661 continue;
662 }
663
664 float minimum_velocity = max_target_velocity;
665 if (landmark_type == "1000001") { // Traffic light
666 minimum_velocity = TL_TARGET_VELOCITY;
667 } else if (landmark_type == "206") { // Stop
668 minimum_velocity = STOP_TARGET_VELOCITY;
669 } else if (landmark_type == "205") { // Yield
670 minimum_velocity = YIELD_TARGET_VELOCITY;
671 } else if (landmark_type == "274") { // Speed limit
672 float value = static_cast<float>(landmark->GetValue()) / 3.6f;
673 value = parameters.GetVehicleTargetVelocity(actor_id, value);
674 minimum_velocity = (value < max_target_velocity) ? value : max_target_velocity;
675 } else {
676 continue;
677 }
678
679 float v = std::max(((max_target_velocity - minimum_velocity) / max_distance) * distance + minimum_velocity, minimum_velocity);
680 landmark_target_velocity = std::min(landmark_target_velocity, v);
681 }
682
683 return landmark_target_velocity;
684}
685
687 const cg::Location vehicle_location,
688 float max_target_velocity) {
689
690 if (waypoint_buffer.size() < 3) {
691 return max_target_velocity;
692 }
693
694 // Start at the waypoint just passed: the arc being cornered on began behind
695 // the front one, and starting at the front makes the speed sawtooth each time
696 // a waypoint is consumed. With several predecessors there is no single arc.
697 std::vector<cg::Location> path;
698 path.reserve(waypoint_buffer.size() + 1u);
699 float path_start_offset = vehicle_location.Distance(waypoint_buffer.front()->GetLocation());
700
701 const std::vector<SimpleWaypointPtr> passed_waypoints =
702 waypoint_buffer.front()->GetPreviousWaypoint();
703 if (passed_waypoints.size() == 1u) {
704 path.push_back(passed_waypoints.front()->GetLocation());
705 path_start_offset = -vehicle_location.Distance(path.front());
706 }
707 for (const auto &waypoint : waypoint_buffer) {
708 path.push_back(waypoint->GetLocation());
709 }
710
711 return GetPathSpeedLimit(path, path_start_offset, CURVATURE_SAMPLE_SPACING,
712 LATERAL_COMFORT_ACCELERATION, TURN_BRAKING_DECELERATION,
713 max_target_velocity);
714}
715
717 pid_state_map.erase(actor_id);
718 teleportation_instance.erase(actor_id);
719 stuck_since.erase(actor_id);
720 recovery_state.erase(actor_id);
721}
722
724 pid_state_map.clear();
726 stuck_since.clear();
727 recovery_state.clear();
728}
729
730} // namespace traffic_manager
731} // 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
static constexpr auto Dot(const Vector3D &a, const Vector3D &b)
Definition Math.h:62
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,...
Vector3D GetForwardVector() const
const std::vector< float > urban_longitudinal_parameters
std::unordered_map< ActorId, RecoveryState > recovery_state
const LocalizationFrame & localization_frame
std::unordered_map< ActorId, double > stuck_since
const std::vector< float > highway_lateral_parameters
std::unordered_map< ActorId, cc::Timestamp > teleportation_instance
bool SafeAfterJunction(const LocalizationData &localization, const bool tl_hazard, const bool collision_emergency_stop)
void Update(const unsigned long index)
const std::vector< float > highway_longitudinal_parameters
float CalculateBaseOffset(const ActorId actor_id, const Buffer &waypoint_buffer, const bool is_target_junction, const uint64_t target_index)
const std::vector< ActorId > & vehicle_id_list
float GetLandmarkTargetVelocity(const SimpleWaypoint &waypoint, const cg::Location vehicle_location, const ActorId actor_id, float max_target_velocity)
float GetTurnTargetVelocity(const Buffer &waypoint_buffer, const cg::Location vehicle_location, float max_target_velocity)
std::unordered_map< ActorId, std::pair< float, bool > > & large_vehicles
bool IsWideTurnSideOccupied(const ActorId actor_id, const cg::Vector3D offset_direction, const float offset_magnitude)
Returns true when the lateral band that the wide-turn offset would swing actor_id into is occupied by...
void RemoveActor(const ActorId actor_id)
void SetCycleTimestamp(const cc::Timestamp &timestamp)
Pins one frame for the whole cycle; reading it per vehicle lets a frame land mid-cycle and skews the ...
const std::vector< float > urban_lateral_parameters
std::unordered_map< ActorId, StateEntry > pid_state_map
MotionPlanStage(const std::vector< ActorId > &vehicle_id_list, SimulationState &simulation_state, const Parameters &parameters, const BufferMap &buffer_map, TrackTraffic &track_traffic, const std::vector< float > &urban_longitudinal_parameters, const std::vector< float > &highway_longitudinal_parameters, const std::vector< float > &urban_lateral_parameters, const std::vector< float > &highway_lateral_parameters, const LocalizationFrame &localization_frame, const CollisionFrame &collision_frame, const TLFrame &tl_frame, ControlFrame &output_array, RandomGenerator &random_device, const LocalMapPtr &local_map, std::unordered_map< ActorId, std::pair< float, bool > > &large_vehicles)
std::pair< bool, float > CollisionHandling(const CollisionHazardData &collision_hazard, const bool tl_hazard, const cg::Vector3D ego_velocity, const cg::Vector3D ego_heading, const float max_target_velocity)
bool GetLargeVehicleWideTurn(const ActorId &actor_id) const
Method to query whether the wide-turn manoeuvre is enabled for a large vehicle (per-vehicle override,...
float GetLaneOffset(const ActorId &actor_id) const
Method to query lane offset for a vehicle.
float GetVehicleTargetVelocity(const ActorId &actor_id, const float speed_limit) const
Method to query target velocity for a vehicle.
bool GetSynchronousMode() const
Method to get synchronous mode.
This is a simple wrapper class on Carla's waypoint object.
WaypointPtr GetWaypoint() const
Returns a carla::shared_ptr to carla::waypoint.
This class holds the state of all the vehicles in the simlation.
cg::Location GetLocation(const ActorId actor_id) const
void UpdateKinematicHybridEndLocation(ActorId actor_id, cg::Location location)
cg::Vector3D GetHeading(const ActorId actor_id) const
float GetSpeedLimit(const ActorId actor_id) const
cg::Rotation GetRotation(const ActorId actor_id) const
cg::Vector3D GetVelocity(const ActorId actor_id) const
bool IsPhysicsEnabled(const ActorId actor_id) const
cg::Vector3D GetDimensions(const ActorId actor_id) const
float GetMaxSteerAngle(const ActorId actor_id) const
ActorIdSet GetPassingVehicles(uint64_t waypoint_id) const
ActorIdSet GetOverlappingVehicles(ActorId actor_id) const
ActuationSignal RunStep(StateEntry present_state, StateEntry previous_state, const std::vector< float > &longitudinal_parameters, const std::vector< float > &lateral_parameters, const float vehicle_speed, const float control_dt=DT, const float lateral_pursuit_steer=0.0f, const float lateral_damping_scale=1.0f, const float steer_authority_correction=1.0f)
This function calculates the actuation signals based on the resent state change of the vehicle to min...
float RelativeVelocityDeviation(const float reference_velocity, const float vehicle_speed, const float target_velocity)
The target is exactly zero behind a stopped vehicle; the floor avoids a 0/0 NaN that the derivative t...
float ShapeReferenceVelocity(const float previous_reference, const float vehicle_speed, const float target_velocity, const float control_dt, const bool emergency_stop)
Reference speed that closes on target_velocity at COMFORT_ACCELERATION instead of stepping to it.
void SmoothActuation(const StateEntry &previous_state, const float control_dt, const float vehicle_speed, ActuationSignal &actuation_signal)
A zero pedal demand bypasses the deadband, so pedals rest exactly at zero and nothing here delays a d...
float LargeVehicleJunctionOffsetProfile(float t, float max_offset, float max_offset_point, float inboard_scale)
Lateral offset profile for the large-vehicle wide turn, as a function of t, the fraction of the junct...
float GetPathSpeedLimit(const std::vector< cg::Location > &path, const float path_start_offset, const float sample_spacing, const float lateral_acceleration, const float braking_deceleration, const float max_speed)
Lowest sqrt(R * lateral_acceleration + 2 * braking_deceleration * distance) over every three consecut...
std::vector< carla::rpc::Command > ControlFrame
std::vector< bool > TLFrame
std::deque< std::shared_ptr< SimpleWaypoint > > Buffer
std::vector< CollisionHazardData > CollisionFrame
std::shared_ptr< InMemoryMap > LocalMapPtr
Definition ALSM.h:38
std::pair< cg::Location, uint64_t > GetTargetData(const Buffer &waypoint_buffer, float target_distance, cg::Location vehicle_location)
Returns the location reached by walking target_distance along the waypoint buffer from vehicle_locati...
std::shared_ptr< SimpleWaypoint > SimpleWaypointPtr
float GetThreePointCircleRadius(cg::Location first_location, cg::Location middle_location, cg::Location last_location)
Returns the radius of the circle defined by three points in the XY plane.
bool IsOffsetSideOccupied(cg::Location ego_location, cg::Vector3D ego_forward, cg::Vector3D offset_direction, float offset_magnitude, float lateral_clearance, float longitudinal_window, const std::vector< std::pair< cg::Location, float > > &neighbours)
Returns true when a neighbouring vehicle sits in the lateral band that the wide-turn offset would swi...
std::unordered_set< ActorId > ActorIdSet
float LargeVehicleOffsetMagnitude(float vehicle_length, float reference_length, float gain, float offset_cap)
Wide-turn offset magnitude scaled by vehicle length: clamp(gain * (vehicle_length - reference_length)...
std::vector< LocalizationData > LocalizationFrame
std::unordered_map< carla::ActorId, Buffer > BufferMap
This file contains definitions of common data structures used in traffic manager.
auto Distance(Location loc) const
constexpr float SquaredLength() const
Vector3D MakeUnitVector(const float epsilon=2.0f *std::numeric_limits< float >::epsilon()) const
Return a unit-length copy of this vector.
Structure to hold the actuation signals.
Structure to hold the controller state.
float reference_velocity
Zero is a safe initial value: the shaping raises it to the current speed.