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
//! Batch command system for efficient multi-actor operations.
//!
//! The command system allows executing multiple operations in a single simulation
//! step, which is significantly more efficient than individual calls.
//!
//! # Examples
//!
//! ```no_run
//! use carla::{client::Client, rpc::Command};
//!
//! let mut client = Client::default();
//! let world = client.world();
//! let bp_lib = world.blueprint_library();
//! let vehicle_bp = bp_lib.find("vehicle.tesla.model3").unwrap();
//! let spawn_points = world.map().recommended_spawn_points();
//!
//! // Create batch of spawn commands
//! let commands = vec![
//!     Command::spawn_actor(
//!         vehicle_bp.clone(),
//!         spawn_points.get(0).unwrap().clone(),
//!         None,
//!     ),
//!     Command::spawn_actor(
//!         vehicle_bp.clone(),
//!         spawn_points.get(1).unwrap().clone(),
//!         None,
//!     ),
//!     Command::spawn_actor(
//!         vehicle_bp.clone(),
//!         spawn_points.get(2).unwrap().clone(),
//!         None,
//!     ),
//! ];
//!
//! // Execute all spawns in one batch
//! let responses = client.apply_batch_sync(commands, false);
//! for response in responses {
//!     if let Some(actor_id) = response.actor_id() {
//!         println!("Spawned actor: {}", actor_id);
//!     }
//! }
//! ```

use crate::{
    client::ActorBlueprint,
    geom::{Location, Transform, Vector3D},
    rpc::{
        ActorId, TrafficLightState, VehicleAckermannControl, VehicleControl, VehicleLightState,
        VehiclePhysicsControl, WalkerControl,
    },
};
use autocxx::WithinUniquePtr;
use carla_sys::carla_rust::{client::FfiCommandBatch, geom::FfiVector3D};
use cxx::UniquePtr;

/// A command to be executed in a batch operation.
///
/// Commands allow efficient batch processing of multiple operations in a single
/// simulation step. Each command type corresponds to a specific actor operation.
pub enum Command {
    /// Spawn a new actor in the simulation.
    ///
    /// # Fields
    /// - `blueprint` - Actor blueprint defining type and attributes
    /// - `transform` - Initial spawn location and rotation
    /// - `parent` - Optional parent actor for attachment
    SpawnActor {
        blueprint: ActorBlueprint,
        transform: Transform,
        parent: Option<ActorId>,
        do_after: Vec<Command>,
    },

    /// Remove an actor from the simulation.
    DestroyActor { actor_id: ActorId },

    /// Apply vehicle control (throttle, steering, brake).
    ApplyVehicleControl {
        actor_id: ActorId,
        control: VehicleControl,
    },

    /// Apply Ackermann steering model control.
    ApplyVehicleAckermannControl {
        actor_id: ActorId,
        control: VehicleAckermannControl,
    },

    /// Apply walker (pedestrian) control.
    ApplyWalkerControl {
        actor_id: ActorId,
        control: WalkerControl,
    },

    /// Set vehicle physics parameters.
    ApplyVehiclePhysicsControl {
        actor_id: ActorId,
        physics_control: VehiclePhysicsControl,
    },

    /// Teleport actor to a new transform.
    ApplyTransform {
        actor_id: ActorId,
        transform: Transform,
    },

    /// Teleport actor to a new location (rotation unchanged).
    ApplyLocation {
        actor_id: ActorId,
        location: Location,
    },

    /// Set walker state (transform and speed).
    ApplyWalkerState {
        actor_id: ActorId,
        transform: Transform,
        speed: f32,
    },

    /// Set actor's target velocity.
    ApplyTargetVelocity {
        actor_id: ActorId,
        velocity: Vector3D,
    },

    /// Set actor's target angular velocity.
    ApplyTargetAngularVelocity {
        actor_id: ActorId,
        angular_velocity: Vector3D,
    },

    /// Apply instantaneous impulse to actor.
    ApplyImpulse {
        actor_id: ActorId,
        impulse: Vector3D,
    },

    /// Apply continuous force to actor.
    ApplyForce { actor_id: ActorId, force: Vector3D },

    /// Apply instantaneous angular impulse (rotation).
    ApplyAngularImpulse {
        actor_id: ActorId,
        impulse: Vector3D,
    },

    /// Apply continuous torque (rotational force).
    ApplyTorque { actor_id: ActorId, torque: Vector3D },

    /// Enable or disable physics simulation for actor.
    SetSimulatePhysics { actor_id: ActorId, enabled: bool },

    /// Enable or disable gravity for actor.
    SetEnableGravity { actor_id: ActorId, enabled: bool },

    /// Enable or disable autopilot for vehicle.
    SetAutopilot {
        actor_id: ActorId,
        enabled: bool,
        tm_port: u16,
    },

    /// Show or hide debug telemetry display.
    ShowDebugTelemetry { actor_id: ActorId, enabled: bool },

    /// Set vehicle light state (headlights, brake lights, etc.).
    SetVehicleLightState {
        actor_id: ActorId,
        light_state: VehicleLightState,
    },

    /// Execute a console command.
    ConsoleCommand { command: String },

    /// Set traffic light state (red, yellow, green).
    SetTrafficLightState {
        actor_id: ActorId,
        state: TrafficLightState,
    },
}

impl Command {
    /// Creates a spawn actor command.
    pub fn spawn_actor(
        blueprint: ActorBlueprint,
        transform: Transform,
        parent: Option<ActorId>,
    ) -> Self {
        Self::SpawnActor {
            blueprint,
            transform,
            parent,
            do_after: Vec::new(),
        }
    }

    /// Chains a command to execute after this spawn completes.
    ///
    /// The chained command will use the newly spawned actor's ID automatically.
    /// Use `actor_id: 0` in the chained command as a placeholder for the future actor.
    ///
    /// This is only valid on `SpawnActor` commands; calling it on other variants
    /// returns `self` unchanged.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use carla::rpc::Command;
    ///
    /// # let blueprint = todo!();
    /// # let transform = todo!();
    /// let cmd = Command::spawn_actor(blueprint, transform, None)
    ///     .then(Command::set_autopilot(0, true, 8000));
    /// ```
    pub fn then(mut self, command: Command) -> Self {
        if let Self::SpawnActor {
            ref mut do_after, ..
        } = self
        {
            do_after.push(command);
        }
        self
    }

    /// Creates a destroy actor command.
    pub fn destroy_actor(actor_id: ActorId) -> Self {
        Self::DestroyActor { actor_id }
    }

    /// Creates an apply vehicle control command.
    pub fn apply_vehicle_control(actor_id: ActorId, control: VehicleControl) -> Self {
        Self::ApplyVehicleControl { actor_id, control }
    }

    /// Creates an apply walker control command.
    pub fn apply_walker_control(actor_id: ActorId, control: WalkerControl) -> Self {
        Self::ApplyWalkerControl { actor_id, control }
    }

    /// Creates an apply transform command.
    pub fn apply_transform(actor_id: ActorId, transform: Transform) -> Self {
        Self::ApplyTransform {
            actor_id,
            transform,
        }
    }

    /// Creates a set autopilot command.
    pub fn set_autopilot(actor_id: ActorId, enabled: bool, tm_port: u16) -> Self {
        Self::SetAutopilot {
            actor_id,
            enabled,
            tm_port,
        }
    }

    /// Creates a console command.
    pub fn console_command(command: String) -> Self {
        Self::ConsoleCommand { command }
    }

    /// Adds this command to an FFI command batch.
    ///
    /// This method translates the Rust Command enum into the corresponding
    /// C++ command by calling the appropriate Add* method on FfiCommandBatch.
    pub(crate) fn add(&self, batch: &mut UniquePtr<FfiCommandBatch>) {
        use carla_sys::carla_rust::client::FfiCommandBatch as Batch;

        match self {
            Self::SpawnActor {
                blueprint,
                transform,
                parent,
                do_after,
            } => {
                let desc = blueprint.inner.MakeActorDescription().within_unique_ptr();
                Batch::AddSpawnActor(
                    batch.pin_mut(),
                    desc,
                    transform.as_ffi(),
                    parent.unwrap_or(0),
                );

                if !do_after.is_empty() {
                    let mut sub_batch = FfiCommandBatch::new().within_unique_ptr();
                    for cmd in do_after {
                        cmd.add(&mut sub_batch);
                    }
                    Batch::AttachDoAfterToLastSpawn(batch.pin_mut(), sub_batch);
                }
            }
            Self::DestroyActor { actor_id } => {
                Batch::AddDestroyActor(batch.pin_mut(), *actor_id);
            }
            Self::ApplyVehicleControl { actor_id, control } => {
                Batch::AddApplyVehicleControl(batch.pin_mut(), *actor_id, control);
            }
            Self::ApplyVehicleAckermannControl { actor_id, control } => {
                Batch::AddApplyVehicleAckermannControl(batch.pin_mut(), *actor_id, control);
            }
            Self::ApplyWalkerControl { actor_id, control } => {
                Batch::AddApplyWalkerControl(batch.pin_mut(), *actor_id, control);
            }
            Self::ApplyVehiclePhysicsControl {
                actor_id,
                physics_control,
            } => {
                let ffi_physics = physics_control.to_cxx();
                Batch::AddApplyVehiclePhysicsControl(batch.pin_mut(), *actor_id, &ffi_physics);
            }
            Self::ApplyTransform {
                actor_id,
                transform,
            } => {
                Batch::AddApplyTransform(batch.pin_mut(), *actor_id, transform.as_ffi());
            }
            Self::ApplyLocation { actor_id, location } => {
                Batch::AddApplyLocation(batch.pin_mut(), *actor_id, location.as_ffi());
            }
            Self::ApplyWalkerState {
                actor_id,
                transform,
                speed,
            } => {
                Batch::AddApplyWalkerState(batch.pin_mut(), *actor_id, transform.as_ffi(), *speed);
            }
            Self::ApplyTargetVelocity { actor_id, velocity } => {
                // SAFETY: FfiVector3D and carla::geom::Vector3D have identical memory layout
                unsafe {
                    let cpp_vec = &*(velocity.as_ffi() as *const FfiVector3D
                        as *const carla_sys::carla::geom::Vector3D);
                    Batch::AddApplyTargetVelocity(batch.pin_mut(), *actor_id, cpp_vec);
                }
            }
            Self::ApplyTargetAngularVelocity {
                actor_id,
                angular_velocity,
            } => {
                // SAFETY: FfiVector3D and carla::geom::Vector3D have identical memory layout
                unsafe {
                    let cpp_vec = &*(angular_velocity.as_ffi() as *const FfiVector3D
                        as *const carla_sys::carla::geom::Vector3D);
                    Batch::AddApplyTargetAngularVelocity(batch.pin_mut(), *actor_id, cpp_vec);
                }
            }
            Self::ApplyImpulse { actor_id, impulse } => {
                // SAFETY: FfiVector3D and carla::geom::Vector3D have identical memory layout
                unsafe {
                    let cpp_vec = &*(impulse.as_ffi() as *const FfiVector3D
                        as *const carla_sys::carla::geom::Vector3D);
                    Batch::AddApplyImpulse(batch.pin_mut(), *actor_id, cpp_vec);
                }
            }
            Self::ApplyForce { actor_id, force } => {
                // SAFETY: FfiVector3D and carla::geom::Vector3D have identical memory layout
                unsafe {
                    let cpp_vec = &*(force.as_ffi() as *const FfiVector3D
                        as *const carla_sys::carla::geom::Vector3D);
                    Batch::AddApplyForce(batch.pin_mut(), *actor_id, cpp_vec);
                }
            }
            Self::ApplyAngularImpulse { actor_id, impulse } => {
                // SAFETY: FfiVector3D and carla::geom::Vector3D have identical memory layout
                unsafe {
                    let cpp_vec = &*(impulse.as_ffi() as *const FfiVector3D
                        as *const carla_sys::carla::geom::Vector3D);
                    Batch::AddApplyAngularImpulse(batch.pin_mut(), *actor_id, cpp_vec);
                }
            }
            Self::ApplyTorque { actor_id, torque } => {
                // SAFETY: FfiVector3D and carla::geom::Vector3D have identical memory layout
                unsafe {
                    let cpp_vec = &*(torque.as_ffi() as *const FfiVector3D
                        as *const carla_sys::carla::geom::Vector3D);
                    Batch::AddApplyTorque(batch.pin_mut(), *actor_id, cpp_vec);
                }
            }
            Self::SetSimulatePhysics { actor_id, enabled } => {
                Batch::AddSetSimulatePhysics(batch.pin_mut(), *actor_id, *enabled);
            }
            Self::SetEnableGravity { actor_id, enabled } => {
                Batch::AddSetEnableGravity(batch.pin_mut(), *actor_id, *enabled);
            }
            Self::SetAutopilot {
                actor_id,
                enabled,
                tm_port,
            } => {
                Batch::AddSetAutopilot(batch.pin_mut(), *actor_id, *enabled, *tm_port);
            }
            Self::ShowDebugTelemetry { actor_id, enabled } => {
                Batch::AddShowDebugTelemetry(batch.pin_mut(), *actor_id, *enabled);
            }
            Self::SetVehicleLightState {
                actor_id,
                light_state,
            } => {
                // Extract the underlying uint32_t flag value from VehicleLightState
                // VehicleLightState is actually VehicleLightState_LightState which has a .flag field
                // But autocxx wraps it, so we need to access the underlying value
                // For now, use a workaround by passing the POD type directly
                unsafe {
                    // SAFETY: VehicleLightState_LightState is a POD type containing just a flag field
                    let flag_value = std::mem::transmute_copy::<_, u32>(light_state);
                    Batch::AddSetVehicleLightState(batch.pin_mut(), *actor_id, flag_value);
                }
            }
            Self::ConsoleCommand { command } => {
                // Convert String to CxxString
                use cxx::let_cxx_string;
                let_cxx_string!(cmd = command);
                Batch::AddConsoleCommand(batch.pin_mut(), &cmd);
            }
            Self::SetTrafficLightState { actor_id, state } => {
                // TrafficLightState is an enum class backed by uint8_t
                // Extract the underlying value
                unsafe {
                    // SAFETY: TrafficLightState is an enum class with uint8_t underlying type
                    let state_value = std::mem::transmute_copy::<_, u8>(state);
                    Batch::AddSetTrafficLightState(batch.pin_mut(), *actor_id, state_value);
                }
            }
        }
    }
}