CARLA
Loading...
Searching...
No Matches
CarlaEpisode.h
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#pragma once
8
18
22#if WITH_ROS2
23 #include <carla/ros2/ROS2.h>
24#endif
25#include <carla/rpc/Actor.h>
30
31#include <util/ue-header-guard-begin.h>
32#include "GameFramework/Pawn.h"
33#include "Materials/MaterialParameterCollectionInstance.h"
34#include <util/ue-header-guard-end.h>
35
36#include "CarlaEpisode.generated.h"
37
38/// A simulation episode.
39///
40/// Each time the level is restarted a new episode is created.
41UCLASS(BlueprintType, Blueprintable)
42class CARLA_API UCarlaEpisode : public UObject
43{
44 GENERATED_BODY()
45
46 // ===========================================================================
47 // -- Constructor ------------------------------------------------------------
48 // ===========================================================================
49
50public:
51
52 UCarlaEpisode(const FObjectInitializer &ObjectInitializer);
53
54 // ===========================================================================
55 // -- Load a new episode -----------------------------------------------------
56 // ===========================================================================
57
58 /// Load a new map and start a new episode.
59 ///
60 /// If @a MapString is empty, the current map is reloaded.
61 UFUNCTION(BlueprintCallable)
62 bool LoadNewEpisode(const FString &MapString, bool ResetSettings = true);
63
64 /// Load a new map generating the mesh from OpenDRIVE data and
65 /// start a new episode.
66 ///
67 /// If @a MapString is empty, it fails.
68 bool LoadNewOpendriveEpisode(
69 const FString &OpenDriveString,
71
72 // ===========================================================================
73 // -- Episode settings -------------------------------------------------------
74 // ===========================================================================
75
76 UFUNCTION(BlueprintCallable)
77 const FEpisodeSettings &GetSettings() const
78 {
79 return EpisodeSettings;
80 }
81
82 UFUNCTION(BlueprintCallable)
83 void ApplySettings(const FEpisodeSettings &Settings);
84
85 // ===========================================================================
86 // -- Retrieve info about this episode ---------------------------------------
87 // ===========================================================================
88
89 /// Return the unique id of this episode.
90 auto GetId() const
91 {
92 return Id;
93 }
94
95 /// Return the name of the map loaded in this episode.
96 UFUNCTION(BlueprintCallable)
97 /// Block (game thread, bounded) until the RecastBuilder run started by the
98 /// last generate_opendrive_world has finished. Returns whether the navmesh
99 /// was built (true when no build is pending).
100 static bool WaitForPendingNavigationBuild(double TimeoutSeconds);
101
102 /// Delete Saved/OpenDrive|Nav/OpenDriveMap.* left by a previous generated
103 /// world (server startup and before each generation).
104 static void ClearGeneratedWorldFiles();
105
106 const FString &GetMapName() const
107 {
108 return MapName;
109 }
110
111 /// Game seconds since the start of this episode.
112 double GetElapsedGameTime() const
113 {
114 return ElapsedGameTime;
115 }
116
117 /// Visual game seconds
118 double GetVisualGameTime() const
119 {
120 return VisualGameTime;
121 }
122
123 void SetVisualGameTime(double Time)
124 {
125 VisualGameTime = Time;
126
127 // update time in material parameters also
128 if (MaterialParameters)
129 {
130 MaterialParameters->SetScalarParameterValue(FName("VisualTime"), VisualGameTime);
131 }
132 }
133
134 /// Return the list of actor definitions that are available to be spawned this
135 /// episode.
136 UFUNCTION(BlueprintCallable)
137 const TArray<FActorDefinition> &GetActorDefinitions() const
138 {
139 return ActorDispatcher->GetActorDefinitions();
140 }
141
142 /// Return the list of recommended spawn points for vehicles.
143 UFUNCTION(BlueprintCallable)
144 TArray<FTransform> GetRecommendedSpawnPoints() const;
145
146 /// Return the geo projection of the map loaded
148 {
149 return MapGeoProjection;
150 }
151
152 // ===========================================================================
153 // -- Retrieve special actors ------------------------------------------------
154 // ===========================================================================
155
156 UFUNCTION(BlueprintCallable)
157 APawn *GetSpectatorPawn() const
158 {
159 return Spectator;
160 }
161
162 UFUNCTION(BlueprintCallable)
163 AWeather *GetWeather() const
164 {
165 return Weather;
166 }
167
169 {
170 return ActorDispatcher->GetActorRegistry();
171 }
172
174 {
175 return ActorDispatcher->GetActorRegistry();
176 }
177
178 // ===========================================================================
179 // -- Actor look up methods --------------------------------------------------
180 // ===========================================================================
181
182 /// Find a Carla actor by id.
183 ///
184 /// If the actor is not found or is pending kill, the returned view is
185 /// invalid.
187 {
188 return ActorDispatcher->GetActorRegistry().FindCarlaActor(ActorId);
189 }
190
191 /// Find the actor view of @a Actor.
192 ///
193 /// If the actor is not found or is pending kill, the returned view is
194 /// invalid.
196 {
197 return ActorDispatcher->GetActorRegistry().FindCarlaActor(Actor);
198 }
199
200 /// Get the description of the Carla actor (sensor) using specific stream id.
201 ///
202 /// If the actor is not found returns an empty string
204 {
205 return ActorDispatcher->GetActorRegistry().GetDescriptionFromStream(StreamId);
206 }
207
208 /// Find the Carla actor (sensor) that owns the stream @a StreamId, or nullptr.
210 {
211 return ActorDispatcher->GetActorRegistry().FindCarlaActorFromStream(StreamId);
212 }
213
214 // ===========================================================================
215 // -- Actor handling methods -------------------------------------------------
216 // ===========================================================================
217
218 /// Spawns an actor based on @a ActorDescription at @a Transform. To properly
219 /// despawn an actor created with this function call DestroyActor.
220 ///
221 /// @return A pair containing the result of the spawn function and a view over
222 /// the actor and its properties. If the status is different of Success the
223 /// view is invalid.
224 TPair<EActorSpawnResultStatus, FCarlaActor*> SpawnActorWithInfo(
225 const FTransform &Transform,
226 FActorDescription thisActorDescription,
227 FCarlaActor::IdType DesiredId = 0);
228
229 /// Spawns an actor based on @a ActorDescription at @a Transform.
230 ///
231 /// @return the actor to be spawned
233 const FTransform &Transform,
234 FActorDescription thisActorDescription)
235 {
236 FTransform NewTransform = Transform;
237 auto result = ActorDispatcher->ReSpawnActor(NewTransform, thisActorDescription);
238 if (Recorder->IsEnabled())
239 {
240 // do something?
241 }
242
243 return result;
244 }
245
246 /// Spawns an actor based on @a ActorDescription at @a Transform. To properly
247 /// despawn an actor created with this function call DestroyActor.
248 ///
249 /// @return nullptr on failure.
250 ///
251 /// @note Special overload for blueprints.
252 UFUNCTION(BlueprintCallable)
253 AActor *SpawnActor(
254 const FTransform &Transform,
255 FActorDescription ActorDescription)
256 {
257 return SpawnActorWithInfo(Transform, std::move(ActorDescription)).Value->GetActor();
258 }
259
260 /// Attach @a Child to @a Parent.
261 ///
262 /// @pre Actors cannot be null.
263 UFUNCTION(BlueprintCallable)
264 void AttachActors(
265 AActor *Child,
266 AActor *Parent,
267 EAttachmentType InAttachmentType = EAttachmentType::Rigid);
268
269 /// @copydoc FActorDispatcher::DestroyActor(AActor*)
270 UFUNCTION(BlueprintCallable)
271 bool DestroyActor(AActor *Actor)
272 {
273 FCarlaActor* CarlaActor = FindCarlaActor(Actor);
274 if (CarlaActor)
275 {
276 carla::rpc::ActorId ActorId = CarlaActor->GetActorId();
277 return DestroyActor(ActorId);
278 }
279 return false;
280 }
281
283 {
284 if (bIsPrimaryServer)
285 {
286 GetFrameData().AddEvent(
287 CarlaRecorderEventDel{ActorId});
288 }
289 if (Recorder->IsEnabled())
290 {
291 // recorder event
292 CarlaRecorderEventDel RecEvent{ActorId};
293 Recorder->AddEvent(std::move(RecEvent));
294 }
295
296 return ActorDispatcher->DestroyActor(ActorId);
297 }
298
299 /// SerializeActor, with the ids the primary's clients know on a Multi-GPU
300 /// secondary (for data a sensor streams to them).
301 carla::rpc::Actor SerializeActorWithPrimaryIds(AActor *Actor) const;
302
303 /// ROS 2: registers the ros_name of each of @a Child's ancestors as one of
304 /// its parent frames.
305 void AddRosParentNames(FCarlaActor &Child);
306
308 {
309 ActorDispatcher->PutActorToSleep(ActorId, this);
310 }
311
313 {
314 ActorDispatcher->WakeActorUp(ActorId, this);
315 }
316
317 // ===========================================================================
318 // -- Other methods ----------------------------------------------------------
319 // ===========================================================================
320
321 /// Create a serializable object describing the actor.
322 carla::rpc::Actor SerializeActor(FCarlaActor* CarlaActor) const;
323
324 /// Create a serializable object describing the actor.
325 /// Can be used to serialized actors that are not in the registry
326 carla::rpc::Actor SerializeActor(AActor* Actor) const;
327
328 // ===========================================================================
329 // -- Private methods and members --------------------------------------------
330 // ===========================================================================
331
333 {
334 return Recorder;
335 }
336
338 {
339 Recorder = Rec;
340 }
341
343 {
344 return Recorder->GetReplayer();
345 }
346
347 std::string StartRecorder(std::string name, bool AdditionalData, bool StopReplayer);
348
349 FIntVector GetCurrentMapOrigin() const { return CurrentMapOrigin; }
350
351 void SetCurrentMapOrigin(const FIntVector& NewOrigin) { CurrentMapOrigin = NewOrigin; }
352
353 FFrameData& GetFrameData() { return FrameData; }
354
355 /// Multi-GPU primary: the world state the frames sent so far carried.
356 FPrimaryWorldState& GetMultiGpuWorldState() { return MultiGpuWorldState; }
357
358 /// A scene light changed: Multi-GPU secondaries get its new state.
359 void MarkSceneLightChanged(int32 LightId)
360 {
361 if (bIsPrimaryServer)
362 {
363 MultiGpuWorldState.ChangedLights.Add(LightId);
364 }
365 }
366
367 FSensorManager& GetSensorManager() { return SensorManager; }
368
369 // ===========================================================================
370 // -- Pedestrian navigation state (server-side walker navigation) -------------
371 // ===========================================================================
372
373 /// Probability that a walker whose navigation starts after this call is a
374 /// "crosser" (may traverse crosswalk/road nav areas). Legacy semantics of
375 /// carla.World.set_pedestrians_cross_factor.
376 void SetPedestriansCrossFactor(float InCrossFactor)
377 {
378 PedestriansCrossFactor = FMath::Clamp(InCrossFactor, 0.0f, 1.0f);
379 }
380
381 /// Seed the RNG behind the crosser draw (and any future navigation
382 /// randomness). Deterministic given the same seed and start order.
383 void SetPedestriansSeed(uint32 InSeed)
384 {
385 PedestriansNavRNG.Initialize(static_cast<int32>(InSeed));
386 }
387
388 /// Draw once per walker at navigation start: crosser or not.
390 {
391 return PedestriansNavRNG.FRand() < PedestriansCrossFactor;
392 }
393
394 bool bIsPrimaryServer = true;
395
396private:
397
398 friend class ACarlaGameModeBase;
400 friend class FCarlaEngine;
401
402 void InitializeAtBeginPlay();
403
404 void EndPlay();
405
407 {
408 ActorDispatcher->Bind(ActorFactory);
409 }
410
411 std::pair<int, FCarlaActor&> TryToCreateReplayerActor(
412 FVector &Location,
413 FVector &Rotation,
414 FActorDescription &ActorDesc,
415 unsigned int desiredId);
416
417 bool SetActorSimulatePhysics(FCarlaActor &CarlaActor, bool bEnabled);
418
419 bool SetActorCollisions(FCarlaActor &CarlaActor, bool bEnabled);
420
421 bool SetActorDead(FCarlaActor &CarlaActor);
422
423 void TickTimers(float DeltaSeconds)
424 {
425 ElapsedGameTime += DeltaSeconds;
426 SetVisualGameTime(VisualGameTime + DeltaSeconds);
427 #if defined(WITH_ROS2)
428 auto ROS2 = carla::ros2::ROS2::GetInstance();
429 if (ROS2->IsEnabled())
430 ROS2->SetTimestamp(GetElapsedGameTime());
431 #endif
432
433 }
434
435 /// Multi-GPU secondary: adopt the primary's clocks for the frame being
436 /// played. Absolute, not accumulated, so frames a secondary never played
437 /// (while it was loading) cause no drift.
438 void SetTimers(double InElapsedGameTime, double InVisualGameTime)
439 {
440 ElapsedGameTime = InElapsedGameTime;
441 SetVisualGameTime(InVisualGameTime);
442 #if defined(WITH_ROS2)
443 auto ROS2 = carla::ros2::ROS2::GetInstance();
444 if (ROS2->IsEnabled())
445 ROS2->SetTimestamp(GetElapsedGameTime());
446 #endif
447 }
448
449 const uint64 Id = 0u;
450
451 // simulation time
452 double ElapsedGameTime = 0.0;
453
454 // visual time (used by clounds and other FX that need to be deterministic)
455 double VisualGameTime = 0.0;
456
457 UPROPERTY(VisibleAnywhere)
458 FString MapName;
459
460 UPROPERTY(VisibleAnywhere)
461 FEpisodeSettings EpisodeSettings;
462
463 UPROPERTY(VisibleAnywhere)
464 UActorDispatcher *ActorDispatcher = nullptr;
465
466 UPROPERTY(VisibleAnywhere)
467 APawn *Spectator = nullptr;
468
469 UPROPERTY(VisibleAnywhere)
470 AWeather *Weather = nullptr;
471
472 UPROPERTY(VisibleAnywhere)
473 UMaterialParameterCollectionInstance *MaterialParameters = nullptr;
474
476
477 carla::geom::GeoProjection MapGeoProjection;
478
479 FIntVector CurrentMapOrigin;
480
481 float PedestriansCrossFactor = 0.0f;
482
483 FRandomStream PedestriansNavRNG = FRandomStream(0);
484
485 FFrameData FrameData;
486
487 FPrimaryWorldState MultiGpuWorldState;
488
489 FSensorManager SensorManager;
490};
491
493 const TSet<carla::rpc::CityObjectLabel> &SemanticTags);
EAttachmentType
FString CarlaGetRelevantTagAsString(const TSet< carla::rpc::CityObjectLabel > &SemanticTags)
Game mode for Autoware maps: when the world settings carry an MGRS data asset, the episode georeferen...
Base class for Carla actor factories.
Base class for the CARLA Game Mode.
Recorder for the simulation.
A registry of all the Carla actors.
A view over an actor and its properties.
Definition CarlaActor.h:25
uint32 IdType
Definition CarlaActor.h:28
IdType GetActorId() const
Definition CarlaActor.h:81
ACarlaRecorder * Recorder
Object in charge of binding ActorDefinitions to spawn functions, as well as keeping the registry of a...
A simulation episode.
FIntVector GetCurrentMapOrigin() const
auto GetId() const
Return the unique id of this episode.
FFrameData & GetFrameData()
FPrimaryWorldState & GetMultiGpuWorldState()
Multi-GPU primary: the world state the frames sent so far carried.
double GetVisualGameTime() const
Visual game seconds.
bool SetActorSimulatePhysics(FCarlaActor &CarlaActor, bool bEnabled)
CarlaReplayer * GetReplayer() const
void PutActorToSleep(carla::rpc::ActorId ActorId)
void SetCurrentMapOrigin(const FIntVector &NewOrigin)
void SetPedestriansCrossFactor(float InCrossFactor)
Probability that a walker whose navigation starts after this call is a "crosser" (may traverse crossw...
FCarlaActor * FindCarlaActor(FCarlaActor::IdType ActorId)
Find a Carla actor by id.
FCarlaActor * FindCarlaActor(AActor *Actor) const
Find the actor view of Actor.
const FString & GetMapName() const
void SetPedestriansSeed(uint32 InSeed)
Seed the RNG behind the crosser draw (and any future navigation randomness).
void RegisterActorFactory(ACarlaActorFactory &ActorFactory)
double GetElapsedGameTime() const
Game seconds since the start of this episode.
FString GetActorDescriptionFromStream(carla::streaming::detail::stream_id_type StreamId)
Get the description of the Carla actor (sensor) using specific stream id.
bool DestroyActor(carla::rpc::ActorId ActorId)
void SetRecorder(ACarlaRecorder *Rec)
AActor * ReSpawnActorWithInfo(const FTransform &Transform, FActorDescription thisActorDescription)
Spawns an actor based on ActorDescription at Transform.
void SetTimers(double InElapsedGameTime, double InVisualGameTime)
Multi-GPU secondary: adopt the primary's clocks for the frame being played.
std::pair< int, FCarlaActor & > TryToCreateReplayerActor(FVector &Location, FVector &Rotation, FActorDescription &ActorDesc, unsigned int desiredId)
void MarkSceneLightChanged(int32 LightId)
A scene light changed: Multi-GPU secondaries get its new state.
void TickTimers(float DeltaSeconds)
bool SetActorCollisions(FCarlaActor &CarlaActor, bool bEnabled)
bool SetActorDead(FCarlaActor &CarlaActor)
FCarlaActor * FindCarlaActorFromStream(carla::streaming::detail::stream_id_type StreamId)
Find the Carla actor (sensor) that owns the stream StreamId, or nullptr.
void SetVisualGameTime(double Time)
const FActorRegistry & GetActorRegistry() const
ACarlaRecorder * GetRecorder() const
FSensorManager & GetSensorManager()
bool DrawWalkerIsCrosser()
Draw once per walker at navigation start: crosser or not.
FActorRegistry & GetActorRegistry()
const carla::geom::GeoProjection & GetGeoProjection() const
Return the geo projection of the map loaded.
void WakeActorUp(carla::rpc::ActorId ActorId)
static std::shared_ptr< ROS2 > GetInstance()
Definition ROS2.h:61
uint32_t ActorId
Definition ActorId.h:14
This file contains definitions of common data structures used in traffic manager.
A definition of a Carla Actor with all the variation and attributes.
A description of a Carla Actor with all its variation.
What a Multi-GPU primary remembers between the frames it sends, to send the world state only when it ...
Definition FrameData.h:106
Seting for map generation from opendrive without additional geometry.