CARLA
Loading...
Searching...
No Matches
CarlaEpisode.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
9#include "Carla.h"
11#include "Carla/Sensor/Sensor.h"
14
19#include "Carla/Game/Tagger.h"
22
24#include <carla/MsgPack.h>
26#include <carla/rpc/String.h>
28
29#include <util/ue-header-guard-begin.h>
30#include "Async/Async.h"
31#include "CollisionQueryParams.h"
32#include "Components/CapsuleComponent.h"
33#include "Engine/OverlapResult.h"
34#include "HAL/PlatformProcess.h"
35#include "Components/WorldPartitionStreamingSourceComponent.h"
36#include "WorldPartition/WorldPartition.h"
37#include "WorldPartition/WorldPartitionSubsystem.h"
38#include "Engine/StaticMeshActor.h"
39#include "EngineUtils.h"
40#include "GameFramework/SpectatorPawn.h"
41#include "GenericPlatform/GenericPlatformProcess.h"
42#include "Kismet/GameplayStatics.h"
43#include "Materials/MaterialParameterCollection.h"
44#include "Materials/MaterialParameterCollectionInstance.h"
45#include "Misc/FileHelper.h"
46#include "Misc/PackageName.h"
47#include "Misc/Paths.h"
48#include <util/ue-header-guard-end.h>
49
50constexpr TCHAR DefaultRecastBuilderPath[] = TEXT(RECASTBUILDER_PATH);
51
52static FString BuildRecastBuilderFile()
53{
54 auto Path = FPaths::RootDir();
55#if PLATFORM_WINDOWS
56 Path += TEXT("Tools/RecastBuilder.exe");
57#else
58 Path += TEXT("Tools/RecastBuilder");
59#endif
60 Path = FPaths::ConvertRelativePathToFull(Path);
61
62 if (FPaths::FileExists(Path))
63 return Path;
64 else
66}
67
68// State of the background RecastBuilder run of the last generated OpenDRIVE
69// world (there is at most one). Readers of the navmesh wait on it.
70static FCriticalSection GNavBuildLock;
71static bool GNavBuildPending = false;
72static bool GNavBuildSucceeded = false;
73
75{
76 const double Start = FPlatformTime::Seconds();
77 bool bLogged = false;
78 for (;;)
79 {
80 {
81 FScopeLock Lock(&GNavBuildLock);
83 {
84 return GNavBuildSucceeded;
85 }
86 }
87 if (!bLogged)
88 {
89 UE_LOG(LogCarla, Log, TEXT("Waiting for RecastBuilder to finish the pedestrian navigation (up to %.0f s)"),
90 TimeoutSeconds);
91 bLogged = true;
92 }
93 if (FPlatformTime::Seconds() - Start > TimeoutSeconds)
94 {
95 UE_LOG(LogCarla, Error, TEXT("RecastBuilder did not finish within %.0f s; "
96 "the pedestrian navigation of this OpenDRIVE world is not available yet"), TimeoutSeconds);
97 return false;
98 }
99 FPlatformProcess::Sleep(0.05f);
100 }
101}
102
104{
105 // Saved/ copies of the generated world outlive the process; a stale pair
106 // (or a .bin from another .xodr) must never shadow the cooked stub.
107 const FString SavedDir = FPaths::ConvertRelativePathToFull(FPaths::ProjectSavedDir());
108 for (const FString &File : {
109 SavedDir / TEXT("OpenDrive/OpenDriveMap.xodr"),
110 SavedDir / TEXT("Nav/OpenDriveMap.obj"),
111 SavedDir / TEXT("Nav/OpenDriveMap.bin")})
112 {
113 if (IFileManager::Get().FileExists(*File))
114 {
115 IFileManager::Get().Delete(*File, false, true, true);
116 UE_LOG(LogCarla, Log, TEXT("Removed stale generated-world file '%s'"), *File);
117 }
118 }
119}
120
122{
123 using TSS = ETrafficSignState;
124 const int32 Kmh = Sign.GetSpeedLimitKmh();
125 if (Kmh > 0)
126 {
127 // km/h always (the OpenDRIVE subtype vocabulary); mph plates are a look, not a unit.
128 return FString::Printf(TEXT("traffic.speed_limit.%d"), Kmh);
129 }
130 switch (Sign.GetTrafficSignState())
131 {
132 case TSS::TrafficLightRed:
133 case TSS::TrafficLightYellow:
134 case TSS::TrafficLightGreen: return TEXT("traffic.traffic_light");
135 case TSS::StopSign: return TEXT("traffic.stop");
136 case TSS::YieldSign: return TEXT("traffic.yield");
137 default: return TEXT("traffic.unknown");
138 }
139}
140
141UCarlaEpisode::UCarlaEpisode(const FObjectInitializer &ObjectInitializer)
142 : Super(ObjectInitializer),
143 Id(URandomEngine::GenerateRandomId())
144{
145 ActorDispatcher = CreateDefaultSubobject<UActorDispatcher>(TEXT("ActorDispatcher"));
146 FrameData.SetEpisode(this);
147
148 const FString AbsoluteRecastBuilderPath = BuildRecastBuilderFile();
149
150 if (!FPaths::FileExists(AbsoluteRecastBuilderPath))
151 {
152 UE_LOG(LogCarla, Warning, TEXT("'RecastBuilder' not present under '%s', "
153 "the binaries for pedestrian navigation will not be created."),
154 *AbsoluteRecastBuilderPath);
155 }
156}
157
158bool UCarlaEpisode::LoadNewEpisode(const FString &MapString, bool ResetSettings)
159{
160 FString FinalPath = UCarlaStatics::FindMapPath(MapString);
161 const bool bIsFileFound = !FinalPath.IsEmpty();
162
163 if (bIsFileFound)
164 {
165 UE_LOG(LogCarla, Warning, TEXT("Loading a new episode: %s"), *FinalPath);
166 UGameplayStatics::OpenLevel(GetWorld(), *FinalPath, true);
167 if (ResetSettings)
169
170 // send 'LOAD_MAP' command to all secondary servers (if any)
172 {
173 UCarlaGameInstance *GameInstance = UCarlaStatics::GetGameInstance(GetWorld());
174 if(GameInstance)
175 {
176 FCarlaEngine *CarlaEngine = GameInstance->GetCarlaEngine();
177 auto SecondaryServer = CarlaEngine->GetSecondaryServer();
178 // A world generated from OpenDRIVE: the secondaries generate the same.
180 TArray<uint8> OpenDrive;
181 if (FPaths::GetBaseFilename(FinalPath).Equals(TEXT("OpenDriveMap"), ESearchCase::IgnoreCase) &&
182 FFileHelper::LoadFileToArray(OpenDrive, *UOpenDrive::GetSavedXODRPath(TEXT("OpenDriveMap")), FILEREAD_Silent))
183 {
184 Extras.opendrive = std::string(reinterpret_cast<const char *>(OpenDrive.GetData()), OpenDrive.Num());
185 const carla::Buffer Parameters = carla::MsgPack::Pack(GameInstance->GetOpendriveGenerationParameters());
186 Extras.generation_parameters =
187 std::string(reinterpret_cast<const char *>(Parameters.data()), Parameters.size());
188 }
189 SecondaryServer->GetCommander().SendLoadMap(std::string(TCHAR_TO_UTF8(*FinalPath)), Extras);
190 }
191 }
192 }
193 return bIsFileFound;
194}
195
196
197
199 const FString &OpenDriveString,
201{
202 if (OpenDriveString.IsEmpty())
203 {
204 UE_LOG(LogCarla, Error, TEXT("The OpenDrive string is empty."));
205 return false;
206 }
207
208 // Build the Map from the OpenDRIVE data
209 const auto CarlaMap = carla::opendrive::OpenDriveParser::Load(
210 carla::rpc::FromLongFString(OpenDriveString));
211
212 // Check the Map is correclty generated
213 if (!CarlaMap.has_value())
214 {
215 UE_LOG(LogCarla, Error, TEXT("The OpenDrive string is invalid or not supported"));
216 return false;
217 }
218
219 // Generate the OBJ (as string)
220 const auto RoadMesh = CarlaMap->GenerateMesh(Params.vertex_distance);
221 const auto CrosswalksMesh = CarlaMap->GetAllCrosswalkMesh();
222 const auto RecastOBJ = (RoadMesh + CrosswalksMesh).GenerateOBJForRecast();
223
224 // Both files go to Saved/: in a packaged build the content dir is backed
225 // by the pak and not writable. The readers (UOpenDrive::FindPathToXODRFile,
226 // FNavigationMesh::Load) look in Saved/ first. RecastBuilder writes the
227 // .bin next to the .obj. Start from a clean slate so a .bin can never
228 // belong to a different .xodr.
231 const FString AbsoluteOBJPath = FPaths::ConvertRelativePathToFull(
232 FPaths::ProjectSavedDir() / TEXT("Nav/OpenDriveMap.obj"));
233
234 // Store the OBJ string to a file in order to that RecastBuilder can load it
235 FFileHelper::SaveStringToFile(
236 carla::rpc::ToLongFString(RecastOBJ),
237 *AbsoluteOBJPath,
238 FFileHelper::EEncodingOptions::ForceUTF8,
239 &IFileManager::Get());
240
241 const FString AbsoluteXODRPath = UOpenDrive::GetSavedXODRPath(TEXT("OpenDriveMap"));
242
243 // Copy the OpenDrive as a file in the serverside
244 FFileHelper::SaveStringToFile(
245 OpenDriveString,
246 *AbsoluteXODRPath,
247 FFileHelper::EEncodingOptions::ForceUTF8,
248 &IFileManager::Get());
249
250 if (!FPaths::FileExists(AbsoluteXODRPath))
251 {
252 UE_LOG(LogCarla, Error, TEXT("ERROR: XODR not copied!"));
253 return false;
254 }
255
256 UCarlaGameInstance * GameInstance = UCarlaStatics::GetGameInstance(GetWorld());
257 if(GameInstance)
258 {
259 GameInstance->SetOpendriveGenerationParameters(Params);
260 }
261 else
262 {
263 carla::log_warning("Missing game instance");
264 }
265
266 const FString AbsoluteRecastBuilderPath = BuildRecastBuilderFile();
267 if (FPaths::FileExists(AbsoluteRecastBuilderPath) &&
269 {
270 // RecastBuilder writes <obj stem>.bin next to the .obj and always exits
271 // 0, so the .bin is the only success signal: drop the previous one first
272 // so a failed build can never hand out last session's navmesh, then watch
273 // the process off the game thread and log the outcome loudly.
274 const FString AbsoluteBinPath = FPaths::ChangeExtension(AbsoluteOBJPath, TEXT("bin"));
275 IFileManager::Get().Delete(*AbsoluteBinPath, false, true, true);
276
277 void *PipeRead = nullptr;
278 void *PipeWrite = nullptr;
279 FPlatformProcess::CreatePipe(PipeRead, PipeWrite);
280
281 /// @todo this can take too long to finish, clients need a method
282 /// to know if the navigation is available or not.
283 FProcHandle RecastHandle = FPlatformProcess::CreateProc(
284 *AbsoluteRecastBuilderPath, *AbsoluteOBJPath,
285 true, true, true, nullptr, 0, nullptr, PipeWrite, nullptr, PipeWrite);
286 if (!RecastHandle.IsValid())
287 {
288 FPlatformProcess::ClosePipe(PipeRead, PipeWrite);
289 UE_LOG(LogCarla, Error, TEXT("RecastBuilder could not be launched ('%s' '%s'); "
290 "no pedestrian navigation for this OpenDRIVE world."),
291 *AbsoluteRecastBuilderPath, *AbsoluteOBJPath);
292 }
293 else
294 {
295 UE_LOG(LogCarla, Log, TEXT("RecastBuilder started: '%s' '%s' -> '%s'"),
296 *AbsoluteRecastBuilderPath, *AbsoluteOBJPath, *AbsoluteBinPath);
297 {
298 FScopeLock Lock(&GNavBuildLock);
299 GNavBuildPending = true;
300 GNavBuildSucceeded = false;
301 }
302 Async(EAsyncExecution::Thread,
303 [RecastHandle, PipeRead, PipeWrite, AbsoluteBinPath, AbsoluteRecastBuilderPath]() mutable
304 {
305 FString Output;
306 while (FPlatformProcess::IsProcRunning(RecastHandle))
307 {
308 Output += FPlatformProcess::ReadPipe(PipeRead);
309 FPlatformProcess::Sleep(0.1f);
310 }
311 Output += FPlatformProcess::ReadPipe(PipeRead);
312 int32 ReturnCode = -1;
313 FPlatformProcess::GetProcReturnCode(RecastHandle, &ReturnCode);
314 FPlatformProcess::CloseProc(RecastHandle);
315 FPlatformProcess::ClosePipe(PipeRead, PipeWrite);
316 Output.TrimEndInline();
317 const bool bSucceeded = ReturnCode == 0 && FPaths::FileExists(AbsoluteBinPath);
318 if (!bSucceeded)
319 {
320 UE_LOG(LogCarla, Error, TEXT("RecastBuilder failed (exit code %d, '%s' %s): no pedestrian "
321 "navigation for this OpenDRIVE world. Output:\n%s"),
322 ReturnCode, *AbsoluteBinPath,
323 FPaths::FileExists(AbsoluteBinPath) ? TEXT("written") : TEXT("missing"), *Output);
324 }
325 else
326 {
327 UE_LOG(LogCarla, Log, TEXT("RecastBuilder finished: navmesh '%s' ready. Output:\n%s"),
328 *AbsoluteBinPath, *Output);
329 }
330 FScopeLock Lock(&GNavBuildLock);
331 GNavBuildPending = false;
332 GNavBuildSucceeded = bSucceeded;
333 });
334 }
335 }
336 else
337 {
338 UE_LOG(LogCarla, Warning, TEXT("'RecastBuilder' not present under '%s', "
339 "the binaries for pedestrian navigation will not be created."),
340 *AbsoluteRecastBuilderPath);
341 }
342
343 return true;
344}
345
347{
348 EpisodeSettings = Settings;
350 {
351 UE_LOG(LogCarla, Warning, TEXT("Setting ActorActiveDistance is smaller that TileStreamingDistance, TileStreamingDistance will be increased"));
353 }
355}
356
358{
360
361 return GM->GetSpawnPointsTransforms();
362}
363
365{
366 carla::rpc::Actor Actor;
367 if (CarlaActor)
368 {
369 Actor = CarlaActor->GetActorInfo()->SerializedData;
370 auto ParentId = CarlaActor->GetParent();
371 if (ParentId)
372 {
373 Actor.parent_id = ParentId;
374 }
375 }
376 else
377 {
378 UE_LOG(LogCarla, Warning, TEXT("Trying to serialize invalid actor"));
379 }
380 return Actor;
381}
382
384{
385 carla::rpc::Actor Serialized = SerializeActor(Actor);
386 if (!bIsPrimaryServer)
387 {
389 if (const FCarlaActor *Mirror = Registry.FindCarlaActor(Serialized.id))
390 {
391 Serialized.id = Mirror->GetPrimaryActorId();
392 }
393 if (Serialized.parent_id != 0u)
394 {
395 if (const FCarlaActor *Parent = Registry.FindCarlaActor(Serialized.parent_id))
396 {
397 Serialized.parent_id = Parent->GetPrimaryActorId();
398 }
399 }
400 }
401 return Serialized;
402}
403
405{
406#if defined(WITH_ROS2)
407 auto ROS2 = carla::ros2::ROS2::GetInstance();
408 if (!ROS2->IsEnabled())
409 {
410 return;
411 }
412 FCarlaActor *CurrentActor = FindCarlaActor(Child.GetParent());
413 while (CurrentActor)
414 {
415 for (const auto &Attr : CurrentActor->GetActorInfo()->Description.Variations)
416 {
417 if (Attr.Key == "ros_name")
418 {
419 ROS2->AddActorParentRosName(static_cast<void*>(Child.GetActor()), static_cast<void*>(CurrentActor->GetActor()));
420 }
421 // NOTE: tier4 also propagated each ancestor's ros_topic_name onto the
422 // child here, but their AddActorRosTopicName used map::insert, so the
423 // dispatcher's earlier per-actor registration (own override or "")
424 // always won and the call was a no-op. Our AddActorRosTopicName is
425 // insert_or_assign (re-registration idempotency), which made the
426 // propagation live and clobbered every attached sensor's own
427 // ros_topic_name with its ancestor's — so it is dropped entirely.
428 }
429 CurrentActor = FindCarlaActor(CurrentActor->GetParent());
430 }
431#endif
432}
433
435{
436 FCarlaActor* CarlaActor = FindCarlaActor(Actor);
437 if (CarlaActor)
438 {
439 return SerializeActor(CarlaActor);
440 }
441 else
442 {
443 carla::rpc::Actor SerializedActor;
444 SerializedActor.id = 0u;
446 TSet<crp::CityObjectLabel> SemanticTags;
447 ATagger::GetTagsOfTaggedActor(*Actor, SemanticTags);
448 FActorDescription Description;
449 Description.Id = TEXT("static.") + CarlaGetRelevantTagAsString(SemanticTags);
450 SerializedActor.description = Description;
451 SerializedActor.semantic_tags.reserve(SemanticTags.Num());
452 for (auto &&Tag : SemanticTags)
453 {
454 using tag_t = decltype(SerializedActor.semantic_tags)::value_type;
455 SerializedActor.semantic_tags.emplace_back(static_cast<tag_t>(Tag));
456 }
457 return SerializedActor;
458 }
459}
460
462 AActor *Child,
463 AActor *Parent,
464 EAttachmentType InAttachmentType)
465{
466 Child->AddActorWorldOffset(FVector(CurrentMapOrigin));
467
468 UActorAttacher::AttachActors(Child, Parent, InAttachmentType);
469
471 {
474 FindCarlaActor(Child)->GetActorId(),
475 FindCarlaActor(Parent)->GetActorId()});
476 }
477 // recorder event
478 if (Recorder->IsEnabled())
479 {
481 {
482 FindCarlaActor(Child)->GetActorId(),
483 FindCarlaActor(Parent)->GetActorId()
484 };
485 Recorder->AddEvent(std::move(RecEvent));
486 }
487}
488
490{
491 auto World = GetWorld();
492 check(World != nullptr);
493 auto PlayerController = UGameplayStatics::GetPlayerController(World, 0);
494 if (PlayerController == nullptr)
495 {
496 UE_LOG(LogCarla, Error, TEXT("Can't find player controller!"));
497 return;
498 }
499 Spectator = PlayerController->GetPawn();
500 if (Spectator != nullptr)
501 {
502 FActorDescription Description;
503 Description.Id = TEXT("spectator");
504 Description.Class = Spectator->GetClass();
506 }
507 else
508 {
509 UE_LOG(LogCarla, Error, TEXT("Can't find spectator!"));
510 }
511
512 // material parameters collection
513 UMaterialParameterCollection *Collection = LoadObject<UMaterialParameterCollection>(nullptr, TEXT("/Game/Carla/Blueprints/Game/CarlaParameters.CarlaParameters"), nullptr, LOAD_None, nullptr);
514 if (Collection != nullptr)
515 {
516 MaterialParameters = World->GetParameterCollectionInstance(Collection);
517 if (MaterialParameters == nullptr)
518 {
519 UE_LOG(LogCarla, Error, TEXT("Can't find CarlaParameters instance!"));
520 }
521 }
522 else
523 {
524 UE_LOG(LogCarla, Error, TEXT("Can't find CarlaParameters asset!"));
525 }
526
527 for (TActorIterator<ATrafficSignBase> It(World); It; ++It)
528 {
529 ATrafficSignBase *Actor = *It;
530 check(Actor != nullptr);
531 FActorDescription Description;
532 Description.Id = UCarlaEpisode_GetTrafficSignId(*Actor);
533 Description.Class = Actor->GetClass();
534 ActorDispatcher->RegisterActor(*Actor, Description);
535 }
536
537 // get the definition id for static.prop.mesh
538 auto Definitions = GetActorDefinitions();
539 uint32 StaticMeshUId = 0;
540 for (auto& Definition : Definitions)
541 {
542 if (Definition.Id == "static.prop.mesh")
543 {
544 StaticMeshUId = Definition.UId;
545 break;
546 }
547 }
548
549 for (TActorIterator<AStaticMeshActor> It(World); It; ++It)
550 {
551 auto Actor = *It;
552 check(Actor != nullptr);
553 auto MeshComponent = Actor->GetStaticMeshComponent();
554 check(MeshComponent != nullptr);
555 if (MeshComponent->Mobility == EComponentMobility::Movable)
556 {
557 FActorDescription Description;
558 Description.Id = TEXT("static.prop.mesh");
559 Description.UId = StaticMeshUId;
560 Description.Class = Actor->GetClass();
561 Description.Variations.Add("mesh_path",
563 MeshComponent->GetStaticMesh()->GetPathName()});
564 Description.Variations.Add("mass",
566 FString::SanitizeFloat(MeshComponent->GetMass())});
567 ActorDispatcher->RegisterActor(*Actor, Description);
568 }
569 }
570}
571
573{
574 // stop recorder and replayer
575 if (Recorder)
576 {
577 Recorder->Stop();
579 {
581 }
582 }
583}
584
585std::string UCarlaEpisode::StartRecorder(std::string Name, bool AdditionalData, bool StopReplayer)
586{
587 std::string result;
588
589 if (Recorder)
590 {
591 result = Recorder->Start(Name, MapName, AdditionalData, StopReplayer);
592 }
593 else
594 {
595 result = "Recorder is not ready";
596 }
597
598 return result;
599}
600
602{
603 // A small probe at the capsule centre: a walker whose capsule merely
604 // touches a facade gets pushed sideways and is fine, and the terrain a
605 // walker spawned at ground level sinks into is not a building.
606 constexpr float ProbeRadius = 10.0f;
607 const UCapsuleComponent *Capsule = Walker.GetCapsuleComponent();
608 const FVector Center = Capsule != nullptr
609 ? Capsule->GetComponentLocation() : Walker.GetActorLocation();
610
611 FCollisionQueryParams Params(SCENE_QUERY_STAT(CarlaWalkerInsideBuilding), false, &Walker);
612 TArray<FOverlapResult> Overlaps;
613 GetWorld()->OverlapMultiByObjectType(
614 Overlaps, Center, FQuat::Identity,
615 FCollisionObjectQueryParams(ECC_WorldStatic),
616 FCollisionShape::MakeSphere(ProbeRadius), Params);
617 for (const FOverlapResult &Overlap : Overlaps)
618 {
619 const UPrimitiveComponent *Component = Overlap.GetComponent();
620 if (Component == nullptr)
621 {
622 continue;
623 }
626 {
627 return true;
628 }
629 }
630 return false;
631}
632
633TPair<EActorSpawnResultStatus, FCarlaActor*> UCarlaEpisode::SpawnActorWithInfo(
634 const FTransform &Transform,
635 FActorDescription thisActorDescription,
636 FCarlaActor::IdType DesiredId)
637{
639 FTransform LocalTransform = Transform;
640 if(LargeMap)
641 {
642 LocalTransform = LargeMap->GlobalToLocalTransform(LocalTransform);
643 }
644
645 // NewTransform.AddToTranslation(-1.0f * FVector(CurrentMapOrigin));
646 auto result = ActorDispatcher->SpawnActor(LocalTransform, thisActorDescription, DesiredId);
647 if (result.Key == EActorSpawnResultStatus::Success &&
648 GetWorld()->GetWorldPartition() != nullptr)
649 {
650 // World Partition map: every physics actor needs the ground under it
651 // resident, mirroring the tile streaming the legacy LargeMapManager
652 // provided on tiled maps. The engine only streams cells around registered
653 // streaming sources; without one, a vehicle spawned away from the
654 // spectator free-falls through the unloaded road.
655 AActor* Actor = result.Value->GetActor();
656 const bool bNeedsGround =
657 Cast<ACarlaWheeledVehicle>(Actor) != nullptr ||
658 Cast<AWalkerBase>(Actor) != nullptr;
659 if (bNeedsGround &&
660 !Actor->FindComponentByClass<UWorldPartitionStreamingSourceComponent>())
661 {
662 // The hero keeps a wide loading ring like the legacy tiled maps gave
663 // it; background traffic only needs the ground in its vicinity.
664 const FActorAttribute* Attribute =
665 thisActorDescription.Variations.Find("role_name");
666 const bool bIsHero = Attribute && (Attribute->Value.Contains("hero") ||
667 Attribute->Value.Contains("ego_vehicle"));
668 auto* Source = NewObject<UWorldPartitionStreamingSourceComponent>(Actor);
669 FStreamingSourceShape Shape;
670 Shape.bUseGridLoadingRange = false;
671 Shape.Radius = bIsHero ? EpisodeSettings.TileStreamingDistance : 20000.0f;
672 Source->Shapes.Add(Shape);
673 Source->RegisterComponent();
674
675 // Physics drops the actor immediately, but cells only stream during the
676 // world partition subsystem update; run one update now and block until
677 // the requested cells are resident so the actor never outruns its
678 // ground.
679 UWorldPartitionSubsystem* WPSubsystem =
680 GetWorld()->GetSubsystem<UWorldPartitionSubsystem>();
681 if (WPSubsystem != nullptr && !WPSubsystem->IsStreamingCompleted(Source))
682 {
683 WPSubsystem->OnUpdateStreamingState();
684 GetWorld()->BlockTillLevelStreamingCompleted();
685 }
686 UE_LOG(LogCarla, Log, TEXT(
687 "WP streaming source on %s (role %s, radius %.0f cm): completed=%d"),
688 *Actor->GetName(), Attribute ? *Attribute->Value : TEXT("none"), Shape.Radius,
689 WPSubsystem ? WPSubsystem->IsStreamingCompleted(Source) : -1);
690
691 // A walker's cells can bring in a building on top of it: the navmesh
692 // covers the terrain under some building footprints, and the building's
693 // cell may only stream in with the walker's own source. Physics then
694 // pushes the walker down through the terrain (#10212). Refuse the spawn
695 // like any other spawn collision instead. Replays and Multi-GPU
696 // secondaries reproduce spawns the primary already accepted.
697 if (AWalkerBase* Walker = Cast<AWalkerBase>(Actor);
698 Walker != nullptr && bIsPrimaryServer &&
699 !Recorder->GetReplayer()->IsEnabled() &&
700 IsWalkerInsideBuilding(*Walker))
701 {
702 UE_LOG(LogCarla, Warning, TEXT(
703 "Walker '%s' spawned inside a building at %s; spawn refused"),
704 *thisActorDescription.Id, *Actor->GetActorLocation().ToString());
705 ActorDispatcher->DestroyActor(result.Value->GetActorId());
706 return MakeTuple(EActorSpawnResultStatus::Collision, nullptr);
707 }
708 }
709 }
710 if (result.Key == EActorSpawnResultStatus::Success && bIsPrimaryServer)
711 {
712 if (Recorder->IsEnabled())
713 {
715 result.Value->GetActorId(),
716 static_cast<uint8_t>(result.Value->GetActorType()),
717 Transform,
718 thisActorDescription
719 );
720 }
722 {
724 result.Value->GetActorId(),
725 static_cast<uint8_t>(result.Value->GetActorType()),
726 Transform,
727 std::move(thisActorDescription));
728 }
729 }
730
731 return result;
732}
EAttachmentType
static bool GNavBuildSucceeded
static FCriticalSection GNavBuildLock
static FString BuildRecastBuilderFile()
static FString UCarlaEpisode_GetTrafficSignId(const ATrafficSignBase &Sign)
constexpr TCHAR DefaultRecastBuilderPath[]
static bool GNavBuildPending
FString CarlaGetRelevantTagAsString(const TSet< carla::rpc::CityObjectLabel > &SemanticTags)
ETrafficSignState
const TArray< FTransform > & GetSpawnPointsTransforms() const
bool IsEnabled(void)
void AddEvent(const CarlaRecorderEventAdd &Event)
CarlaReplayer * GetReplayer(void)
std::string Start(std::string Name, FString MapName, bool AdditionalData=false, bool StopReplayer=true)
void CreateRecorderEventAdd(uint32_t DatabaseId, uint8_t Type, const FTransform &Transform, FActorDescription ActorDescription)
FTransform GlobalToLocalTransform(const FTransform &InTransform) const
static void GetTagsOfTaggedActor(const AActor &Actor, TSet< crp::CityObjectLabel > &Tags)
Retrieve the tags of an already tagged actor.
Definition Tagger.cpp:221
static crp::CityObjectLabel GetTagOfTaggedComponent(const UPrimitiveComponent &Component)
Retrieve the tag of an already tagged component.
Definition Tagger.cpp:213
ETrafficSignState GetTrafficSignState() const
int32 GetSpeedLimitKmh() const
km/h this sign limits to, -1 when it is not a speed-limit sign.
bool IsEnabled(void)
void Stop(bool KeepActors=false)
A registry of all the Carla actors.
FCarlaActor * FindCarlaActor(IdType Id)
A view over an actor and its properties.
Definition CarlaActor.h:25
IdType GetParent() const
Definition CarlaActor.h:121
AActor * GetActor()
Definition CarlaActor.h:91
uint32 IdType
Definition CarlaActor.h:28
const FActorInfo * GetActorInfo() const
Definition CarlaActor.h:101
IdType GetActorId() const
Definition CarlaActor.h:81
std::shared_ptr< carla::multigpu::Router > GetSecondaryServer()
Definition CarlaEngine.h:99
static FOnEpisodeSettingsChange OnEpisodeSettingsChange
void SetEpisode(UCarlaEpisode *ThisEpisode)
Definition FrameData.h:163
void AddEvent(const CarlaRecorderEventAdd &Event)
void CreateRecorderEventAdd(uint32_t DatabaseId, uint8_t Type, const FTransform &Transform, FActorDescription ActorDescription, bool bAddOtherRelatedInfo=true)
A rigid transform in CARLA's / Unreal's left-handed frame: x forward, y right, z up,...
static void AttachActors(AActor *Child, AActor *Parent, EAttachmentType AttachmentType)
const FActorRegistry & GetActorRegistry() const
FCarlaActor * RegisterActor(AActor &Actor, FActorDescription ActorDescription, FActorRegistry::IdType DesiredId=0)
Register an actor that was not created using "SpawnActor" function but that should be kept in the reg...
bool DestroyActor(FCarlaActor::IdType ActorId)
Destroys an actor, properly removing it from the registry.
TPair< EActorSpawnResultStatus, FCarlaActor * > SpawnActor(const FTransform &Transform, FActorDescription ActorDescription, FCarlaActor::IdType DesiredId=0)
Spawns an actor based on ActorDescription at Transform.
static FBoundingBox GetActorBoundingBox(const AActor *Actor, uint8 InTagQueried=0xFF)
Compute the bounding box of the given Carla actor.
FFrameData & GetFrameData()
carla::rpc::Actor SerializeActor(FCarlaActor *CarlaActor) const
Create a serializable object describing the actor.
FEpisodeSettings EpisodeSettings
static void ClearGeneratedWorldFiles()
Delete Saved/OpenDrive|Nav/OpenDriveMap.
UCarlaEpisode(const FObjectInitializer &ObjectInitializer)
FIntVector CurrentMapOrigin
bool LoadNewOpendriveEpisode(const FString &OpenDriveString, const carla::rpc::OpendriveGenerationParameters &Params)
Load a new map generating the mesh from OpenDRIVE data and start a new episode.
const TArray< FActorDefinition > & GetActorDefinitions() const
Return the list of actor definitions that are available to be spawned this episode.
FCarlaActor * FindCarlaActor(FCarlaActor::IdType ActorId)
Find a Carla actor by id.
UActorDispatcher * ActorDispatcher
std::string StartRecorder(std::string name, bool AdditionalData, bool StopReplayer)
carla::rpc::Actor SerializeActorWithPrimaryIds(AActor *Actor) const
SerializeActor, with the ids the primary's clients know on a Multi-GPU secondary (for data a sensor s...
const uint64 Id
void ApplySettings(const FEpisodeSettings &Settings)
static bool WaitForPendingNavigationBuild(double TimeoutSeconds)
Return the name of the map loaded in this episode.
TPair< EActorSpawnResultStatus, FCarlaActor * > SpawnActorWithInfo(const FTransform &Transform, FActorDescription thisActorDescription, FCarlaActor::IdType DesiredId=0)
Spawns an actor based on ActorDescription at Transform.
UMaterialParameterCollectionInstance * MaterialParameters
APawn * Spectator
bool IsWalkerInsideBuilding(const AWalkerBase &Walker) const
True if the centre of Walker's capsule is inside the collision of a building or wall,...
friend class ACarlaGameModeBase
ACarlaRecorder * Recorder
void InitializeAtBeginPlay()
void AddRosParentNames(FCarlaActor &Child)
ROS 2: registers the ros_name of each of Child's ancestors as one of its parent frames.
FFrameData FrameData
bool LoadNewEpisode(const FString &MapString, bool ResetSettings=true)
Load a new map and start a new episode.
void AttachActors(AActor *Child, AActor *Parent, EAttachmentType InAttachmentType=EAttachmentType::Rigid)
Attach Child to Parent.
TArray< FTransform > GetRecommendedSpawnPoints() const
Return the list of recommended spawn points for vehicles.
friend class FCarlaEngine
The game instance contains elements that must be kept alive in between levels.
const carla::rpc::OpendriveGenerationParameters & GetOpendriveGenerationParameters() const
FCarlaEngine * GetCarlaEngine()
void SetOpendriveGenerationParameters(const carla::rpc::OpendriveGenerationParameters &Parameters)
static FString FindMapPath(const FString &MapName)
static UCarlaGameInstance * GetGameInstance(const UObject *WorldContextObject)
static ALargeMapManager * GetLargeMapManager(const UObject *WorldContextObject)
static ACarlaGameModeBase * GetGameMode(const UObject *WorldContextObject)
static FString GetSavedXODRPath(const FString &MapName)
Where a generated OpenDRIVE world stores its xodr: <ProjectSavedDir>/OpenDrive/<MapName>....
A piece of raw data.
const value_type * data() const noexcept
Direct access to the allocated memory or nullptr if no memory is allocated.
size_type size() const noexcept
static Buffer Pack(const T &obj)
Definition MsgPack.h:19
static std::optional< road::Map > Load(const std::string &opendrive)
static std::shared_ptr< ROS2 > GetInstance()
Definition ROS2.h:61
std::vector< uint8_t > semantic_tags
Definition rpc/Actor.h:33
ActorId parent_id
Definition rpc/Actor.h:27
ActorDescription description
Definition rpc/Actor.h:29
geom::BoundingBox bounding_box
Definition rpc/Actor.h:31
An actor attribute, may be an intrinsic (non-modifiable) attribute of the actor or an user-defined ac...
A description of a Carla Actor with all its variation.
TMap< FString, FActorAttribute > Variations
User selected variations of the actor.
TSubclassOf< AActor > Class
Class of the actor to be spawned.
uint32 UId
UId of the definition in which this description was based.
FActorDescription Description
Definition ActorInfo.h:21
carla::rpc::Actor SerializedData
Definition ActorInfo.h:27
What a LOAD_MAP carries besides the map: for a world the primary generated from OpenDRIVE (generate_o...
Definition commands.h:51
std::optional< std::string > generation_parameters
Definition commands.h:53
std::optional< std::string > opendrive
Definition commands.h:52
Seting for map generation from opendrive without additional geometry.