carla 0.14.1

Rust client library for Carla simulator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! BasicAgent implementation for autonomous navigation.

use super::{
    agent_core::{AgentCore, AgentCoreConfig, LaneChangeDirection},
    global_route_planner::GlobalRoutePlanner,
    local_planner::LocalPlannerConfig,
    types::{Agent, RoadOption},
};
use crate::{
    agents::tools::get_speed,
    client::{ActorBase, Map, Vehicle, Waypoint},
    error::{MapError, OperationError, Result},
    geom::Location,
    rpc::VehicleControl,
};

/// Configuration options for BasicAgent.
#[derive(Debug, Clone)]
pub struct BasicAgentConfig {
    /// Target speed in km/h
    pub target_speed: f32,
    /// Agent core configuration
    pub core_config: AgentCoreConfig,
    /// Local planner configuration
    pub local_config: LocalPlannerConfig,
}

impl Default for BasicAgentConfig {
    fn default() -> Self {
        Self {
            target_speed: 20.0,
            core_config: AgentCoreConfig::default(),
            local_config: LocalPlannerConfig {
                target_speed: 20.0,
                ..Default::default()
            },
        }
    }
}

/// BasicAgent provides traffic-aware navigation with obstacle and traffic light detection.
///
/// # Examples
/// ```no_run
/// use carla::{
///     agents::navigation::{BasicAgent, BasicAgentConfig},
///     client::Vehicle,
///     geom::Location,
/// };
///
/// # fn example(vehicle: Vehicle) -> carla::Result<()> {
/// let config = BasicAgentConfig::default();
/// let mut agent = BasicAgent::new(vehicle, config, None, None)?;
///
/// // Set destination
/// let destination = Location {
///     x: 100.0,
///     y: 50.0,
///     z: 0.3,
/// };
/// agent.set_destination(destination, None, true)?;
///
/// // Control loop
/// while !agent.done() {
///     let control = agent.run_step()?;
///     // Apply control to vehicle
/// }
/// # Ok(())
/// # }
/// ```
pub struct BasicAgent {
    core: AgentCore,
    target_speed: f32,
}

impl BasicAgent {
    /// Creates a new BasicAgent.
    ///
    /// # Arguments
    /// * `vehicle` - The vehicle to control
    /// * `config` - Agent configuration
    /// * `map_inst` - Optional pre-loaded map instance
    /// * `grp_inst` - Optional pre-loaded GlobalRoutePlanner instance
    pub fn new(
        vehicle: Vehicle,
        config: BasicAgentConfig,
        map_inst: Option<Map>,
        grp_inst: Option<GlobalRoutePlanner>,
    ) -> Result<Self> {
        let target_speed = config.target_speed;

        let core = AgentCore::new(
            vehicle,
            map_inst,
            grp_inst,
            config.core_config,
            config.local_config,
        )?;

        Ok(Self { core, target_speed })
    }

    /// Sets the target speed in km/h.
    pub fn set_target_speed(&mut self, speed: f32) {
        self.target_speed = speed;
        self.core.local_planner.set_speed(speed);
    }

    /// Enables or disables speed limit following.
    pub fn follow_speed_limits(&mut self, value: bool) {
        self.core.local_planner.follow_speed_limits(value);
    }

    /// Sets a navigation destination.
    ///
    /// # Arguments
    /// * `end_location` - Target destination
    /// * `start_location` - Optional starting location (defaults to vehicle position)
    /// * `clean_queue` - Whether to clear existing route
    pub fn set_destination(
        &mut self,
        end_location: Location,
        start_location: Option<Location>,
        clean_queue: bool,
    ) -> Result<()> {
        let start_location = if let Some(loc) = start_location {
            loc
        } else if clean_queue {
            if let Some((wp, _)) = self
                .core
                .local_planner
                .get_incoming_waypoint_and_direction(0)
            {
                wp.transform().location
            } else {
                self.core.vehicle.transform()?.location
            }
        } else if let Some((wp, _)) = self.core.local_planner.get_plan().last() {
            wp.transform().location
        } else {
            self.core.vehicle.transform()?.location
        };

        // Compute route using global planner
        let route = self
            .core
            .global_planner
            .trace_route(start_location, end_location)?;

        // Set route in local planner
        self.core
            .local_planner
            .set_global_plan(route, true, clean_queue);

        Ok(())
    }

    /// Sets a pre-computed global plan.
    pub fn set_global_plan(
        &mut self,
        plan: Vec<(Waypoint, RoadOption)>,
        stop_waypoint_creation: bool,
        clean_queue: bool,
    ) {
        self.core
            .local_planner
            .set_global_plan(plan, stop_waypoint_creation, clean_queue);
    }

    /// Computes a route between two waypoints.
    pub fn trace_route(
        &self,
        start_waypoint: &Waypoint,
        end_waypoint: &Waypoint,
    ) -> Result<Vec<(Waypoint, RoadOption)>> {
        let start_location = start_waypoint.transform().location;
        let end_location = end_waypoint.transform().location;
        self.core
            .global_planner
            .trace_route(start_location, end_location)
    }

    /// Checks if the destination has been reached.
    pub fn done(&self) -> bool {
        self.core.local_planner.done()
    }

    /// Executes one navigation step.
    ///
    /// # Returns
    /// VehicleControl command to apply to the vehicle
    pub fn run_step(&mut self) -> Result<VehicleControl> {
        self.run_step_debug(false)
    }

    /// Executes one navigation step with optional debug output.
    pub fn run_step_debug(&mut self, debug: bool) -> Result<VehicleControl> {
        let mut hazard_detected = false;

        // Get vehicle speed
        let vehicle_speed = get_speed(&self.core.vehicle) / 3.6; // Convert to m/s

        // Check for vehicle obstacles
        let max_vehicle_distance =
            self.core.base_vehicle_threshold + self.core.speed_ratio * vehicle_speed;
        let obstacle_result = self.core.vehicle_obstacle_detected(max_vehicle_distance)?;

        if obstacle_result.obstacle_was_found {
            hazard_detected = true;
            if debug {
                println!(
                    "BasicAgent: Vehicle obstacle detected at {:.1}m",
                    obstacle_result.distance
                );
            }
        }

        // Check for traffic lights
        let max_tlight_distance =
            self.core.base_tlight_threshold + self.core.speed_ratio * vehicle_speed;
        let traffic_light_result = self.core.affected_by_traffic_light(max_tlight_distance)?;

        if traffic_light_result.traffic_light_was_found {
            hazard_detected = true;
            if debug {
                println!("BasicAgent: Red traffic light detected");
            }
        }

        // Get control from local planner
        let mut control = self.core.local_planner.run_step(debug)?;

        // Apply emergency stop if hazard detected
        if hazard_detected {
            control = self.add_emergency_stop(control);
            if debug {
                println!("BasicAgent: Emergency stop applied");
            }
        }

        Ok(control)
    }

    /// Applies emergency stop to a control.
    pub fn add_emergency_stop(&self, mut control: VehicleControl) -> VehicleControl {
        control.throttle = 0.0;
        control.brake = self.core.max_brake;
        control.hand_brake = false;
        control
    }

    /// Sets whether to ignore traffic lights.
    pub fn ignore_traffic_lights(&mut self, active: bool) {
        self.core.ignore_traffic_lights(active);
    }

    /// Sets whether to ignore stop signs.
    pub fn ignore_stop_signs(&mut self, active: bool) {
        self.core.ignore_stop_signs(active);
    }

    /// Sets whether to ignore vehicles.
    pub fn ignore_vehicles(&mut self, active: bool) {
        self.core.ignore_vehicles(active);
    }

    /// Gets a reference to the local planner (for advanced use).
    pub fn local_planner(&self) -> &super::local_planner::LocalPlanner {
        &self.core.local_planner
    }

    /// Gets a reference to the global planner (for advanced use).
    pub fn global_planner(&self) -> &GlobalRoutePlanner {
        &self.core.global_planner
    }

    /// Executes a lane change maneuver.
    ///
    /// # Arguments
    /// * `direction` - Direction to change lanes (left or right)
    /// * `same_lane_time` - Time (seconds) to travel in current lane before starting change
    /// * `other_lane_time` - Time (seconds) to travel in new lane after completing change
    /// * `lane_change_time` - Time (seconds) to perform the lane change
    ///
    /// # Returns
    /// Ok(()) if lane change path was generated and applied, Err if not possible
    pub fn lane_change(
        &mut self,
        direction: LaneChangeDirection,
        same_lane_time: f32,
        other_lane_time: f32,
        lane_change_time: f32,
    ) -> Result<()> {
        // Get current speed to convert time to distance
        let speed = get_speed(&self.core.vehicle) / 3.6; // Convert km/h to m/s
        let speed = speed.max(1.0); // Minimum 1 m/s to avoid division by zero

        // Convert times to distances
        let distance_same_lane = speed * same_lane_time;
        let distance_other_lane = speed * other_lane_time;
        let lane_change_distance = speed * lane_change_time;

        // Get current waypoint
        let current_waypoint = if let Some((wp, _)) = self
            .core
            .local_planner
            .get_incoming_waypoint_and_direction(0)
        {
            wp
        } else {
            // Use vehicle location if no waypoint in queue
            let vehicle_location = self.core.vehicle.transform()?.location;
            self.core
                .map
                .waypoint_at(&vehicle_location)?
                .ok_or_else(|| MapError::InvalidWaypoint {
                    location: format!("{:?}", vehicle_location),
                    reason: "Failed to get waypoint from vehicle location".to_string(),
                })?
        };

        // Generate lane change path
        let step_distance = 2.0; // 2 meters between waypoints
        let path = AgentCore::generate_lane_change_path(
            &current_waypoint,
            direction,
            distance_same_lane,
            distance_other_lane,
            lane_change_distance,
            true, // Check if lane change is possible
            step_distance,
        );

        if path.is_empty() {
            return Err(OperationError::InvalidTransform {
                transform: format!("{:?}", current_waypoint.transform()),
                reason: "Lane change not possible".to_string(),
            }
            .into());
        }

        // Apply the lane change path
        self.set_global_plan(path, true, true);

        Ok(())
    }
}

impl Agent for BasicAgent {
    fn run_step(&mut self) -> Result<VehicleControl> {
        self.run_step()
    }

    fn done(&self) -> bool {
        self.done()
    }

    fn set_destination(
        &mut self,
        end_location: Location,
        start_location: Option<Location>,
        clean_queue: bool,
    ) -> Result<()> {
        self.set_destination(end_location, start_location, clean_queue)
    }

    fn set_target_speed(&mut self, speed: f32) {
        self.set_target_speed(speed)
    }

    fn set_global_plan(
        &mut self,
        plan: Vec<(Waypoint, RoadOption)>,
        stop_waypoint_creation: bool,
        clean_queue: bool,
    ) {
        self.set_global_plan(plan, stop_waypoint_creation, clean_queue)
    }

    fn trace_route(
        &self,
        start_waypoint: &Waypoint,
        end_waypoint: &Waypoint,
    ) -> Result<Vec<(Waypoint, RoadOption)>> {
        self.trace_route(start_waypoint, end_waypoint)
    }

    fn ignore_traffic_lights(&mut self, active: bool) {
        self.ignore_traffic_lights(active)
    }

    fn ignore_stop_signs(&mut self, active: bool) {
        self.ignore_stop_signs(active)
    }

    fn ignore_vehicles(&mut self, active: bool) {
        self.ignore_vehicles(active)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_basic_agent_config_default() {
        let config = BasicAgentConfig::default();
        assert_eq!(config.target_speed, 20.0);
    }

    #[test]
    fn test_emergency_stop() {
        // Test emergency stop logic without needing a vehicle
        let control = VehicleControl {
            throttle: 0.5,
            steer: 0.1,
            brake: 0.0,
            hand_brake: false,
            reverse: false,
            manual_gear_shift: false,
            gear: 0,
        };

        let max_brake = 0.5;
        let mut stopped_control = control;
        stopped_control.throttle = 0.0;
        stopped_control.brake = max_brake;

        assert_eq!(stopped_control.throttle, 0.0);
        assert_eq!(stopped_control.brake, 0.5);
    }
}