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>
54 auto Path = FPaths::RootDir();
56 Path += TEXT(
"Tools/RecastBuilder.exe");
58 Path += TEXT(
"Tools/RecastBuilder");
60 Path = FPaths::ConvertRelativePathToFull(Path);
62 if (FPaths::FileExists(Path))
76 const double Start = FPlatformTime::Seconds();
89 UE_LOG(LogCarla, Log, TEXT(
"Waiting for RecastBuilder to finish the pedestrian navigation (up to %.0f s)"),
93 if (FPlatformTime::Seconds() - Start > TimeoutSeconds)
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);
99 FPlatformProcess::Sleep(0.05f);
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")})
113 if (IFileManager::Get().FileExists(*File))
115 IFileManager::Get().Delete(*File,
false,
true,
true);
116 UE_LOG(LogCarla, Log, TEXT(
"Removed stale generated-world file '%s'"), *File);
128 return FString::Printf(TEXT(
"traffic.speed_limit.%d"), Kmh);
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");
142 : Super(ObjectInitializer),
145 ActorDispatcher = CreateDefaultSubobject<UActorDispatcher>(TEXT(
"ActorDispatcher"));
150 if (!FPaths::FileExists(AbsoluteRecastBuilderPath))
152 UE_LOG(LogCarla, Warning, TEXT(
"'RecastBuilder' not present under '%s', "
153 "the binaries for pedestrian navigation will not be created."),
154 *AbsoluteRecastBuilderPath);
161 const bool bIsFileFound = !FinalPath.IsEmpty();
165 UE_LOG(LogCarla, Warning, TEXT(
"Loading a new episode: %s"), *FinalPath);
166 UGameplayStatics::OpenLevel(GetWorld(), *FinalPath,
true);
180 TArray<uint8> OpenDrive;
181 if (FPaths::GetBaseFilename(FinalPath).Equals(TEXT(
"OpenDriveMap"), ESearchCase::IgnoreCase) &&
184 Extras.
opendrive = std::string(
reinterpret_cast<const char *
>(OpenDrive.GetData()), OpenDrive.Num());
187 std::string(
reinterpret_cast<const char *
>(Parameters.
data()), Parameters.
size());
189 SecondaryServer->GetCommander().SendLoadMap(std::string(TCHAR_TO_UTF8(*FinalPath)), Extras);
199 const FString &OpenDriveString,
202 if (OpenDriveString.IsEmpty())
204 UE_LOG(LogCarla, Error, TEXT(
"The OpenDrive string is empty."));
210 carla::rpc::FromLongFString(OpenDriveString));
213 if (!CarlaMap.has_value())
215 UE_LOG(LogCarla, Error, TEXT(
"The OpenDrive string is invalid or not supported"));
221 const auto CrosswalksMesh = CarlaMap->GetAllCrosswalkMesh();
222 const auto RecastOBJ = (RoadMesh + CrosswalksMesh).GenerateOBJForRecast();
231 const FString AbsoluteOBJPath = FPaths::ConvertRelativePathToFull(
232 FPaths::ProjectSavedDir() / TEXT(
"Nav/OpenDriveMap.obj"));
235 FFileHelper::SaveStringToFile(
236 carla::rpc::ToLongFString(RecastOBJ),
238 FFileHelper::EEncodingOptions::ForceUTF8,
239 &IFileManager::Get());
244 FFileHelper::SaveStringToFile(
247 FFileHelper::EEncodingOptions::ForceUTF8,
248 &IFileManager::Get());
250 if (!FPaths::FileExists(AbsoluteXODRPath))
252 UE_LOG(LogCarla, Error, TEXT(
"ERROR: XODR not copied!"));
263 carla::log_warning(
"Missing game instance");
267 if (FPaths::FileExists(AbsoluteRecastBuilderPath) &&
274 const FString AbsoluteBinPath = FPaths::ChangeExtension(AbsoluteOBJPath, TEXT(
"bin"));
275 IFileManager::Get().Delete(*AbsoluteBinPath,
false,
true,
true);
277 void *PipeRead =
nullptr;
278 void *PipeWrite =
nullptr;
279 FPlatformProcess::CreatePipe(PipeRead, PipeWrite);
283 FProcHandle RecastHandle = FPlatformProcess::CreateProc(
284 *AbsoluteRecastBuilderPath, *AbsoluteOBJPath,
285 true,
true,
true,
nullptr, 0,
nullptr, PipeWrite,
nullptr, PipeWrite);
286 if (!RecastHandle.IsValid())
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);
295 UE_LOG(LogCarla, Log, TEXT(
"RecastBuilder started: '%s' '%s' -> '%s'"),
296 *AbsoluteRecastBuilderPath, *AbsoluteOBJPath, *AbsoluteBinPath);
302 Async(EAsyncExecution::Thread,
303 [RecastHandle, PipeRead, PipeWrite, AbsoluteBinPath, AbsoluteRecastBuilderPath]()
mutable
306 while (FPlatformProcess::IsProcRunning(RecastHandle))
308 Output += FPlatformProcess::ReadPipe(PipeRead);
309 FPlatformProcess::Sleep(0.1f);
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);
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);
327 UE_LOG(LogCarla, Log, TEXT(
"RecastBuilder finished: navmesh '%s' ready. Output:\n%s"),
328 *AbsoluteBinPath, *Output);
338 UE_LOG(LogCarla, Warning, TEXT(
"'RecastBuilder' not present under '%s', "
339 "the binaries for pedestrian navigation will not be created."),
340 *AbsoluteRecastBuilderPath);
351 UE_LOG(LogCarla, Warning, TEXT(
"Setting ActorActiveDistance is smaller that TileStreamingDistance, TileStreamingDistance will be increased"));
373 Actor.parent_id = ParentId;
378 UE_LOG(LogCarla, Warning, TEXT(
"Trying to serialize invalid actor"));
391 Serialized.
id = Mirror->GetPrimaryActorId();
397 Serialized.
parent_id = Parent->GetPrimaryActorId();
406#if defined(WITH_ROS2)
408 if (!ROS2->IsEnabled())
417 if (Attr.Key ==
"ros_name")
419 ROS2->AddActorParentRosName(
static_cast<void*
>(Child.
GetActor()),
static_cast<void*
>(CurrentActor->
GetActor()));
444 SerializedActor.
id = 0u;
446 TSet<crp::CityObjectLabel> SemanticTags;
452 for (
auto &&Tag : SemanticTags)
454 using tag_t =
decltype(SerializedActor.
semantic_tags)::value_type;
455 SerializedActor.
semantic_tags.emplace_back(
static_cast<tag_t
>(Tag));
457 return SerializedActor;
491 auto World = GetWorld();
492 check(World !=
nullptr);
493 auto PlayerController = UGameplayStatics::GetPlayerController(World, 0);
494 if (PlayerController ==
nullptr)
496 UE_LOG(LogCarla, Error, TEXT(
"Can't find player controller!"));
503 Description.
Id = TEXT(
"spectator");
509 UE_LOG(LogCarla, Error, TEXT(
"Can't find spectator!"));
513 UMaterialParameterCollection *Collection = LoadObject<UMaterialParameterCollection>(
nullptr, TEXT(
"/Game/Carla/Blueprints/Game/CarlaParameters.CarlaParameters"),
nullptr, LOAD_None,
nullptr);
514 if (Collection !=
nullptr)
519 UE_LOG(LogCarla, Error, TEXT(
"Can't find CarlaParameters instance!"));
524 UE_LOG(LogCarla, Error, TEXT(
"Can't find CarlaParameters asset!"));
527 for (TActorIterator<ATrafficSignBase> It(World); It; ++It)
530 check(Actor !=
nullptr);
533 Description.
Class = Actor->GetClass();
539 uint32 StaticMeshUId = 0;
540 for (
auto& Definition : Definitions)
542 if (Definition.Id ==
"static.prop.mesh")
544 StaticMeshUId = Definition.UId;
549 for (TActorIterator<AStaticMeshActor> It(World); It; ++It)
552 check(Actor !=
nullptr);
553 auto MeshComponent = Actor->GetStaticMeshComponent();
554 check(MeshComponent !=
nullptr);
555 if (MeshComponent->Mobility == EComponentMobility::Movable)
558 Description.
Id = TEXT(
"static.prop.mesh");
559 Description.
UId = StaticMeshUId;
560 Description.
Class = Actor->GetClass();
563 MeshComponent->GetStaticMesh()->GetPathName()});
566 FString::SanitizeFloat(MeshComponent->GetMass())});
595 result =
"Recorder is not ready";
606 constexpr float ProbeRadius = 10.0f;
607 const UCapsuleComponent *Capsule = Walker.GetCapsuleComponent();
608 const FVector Center = Capsule !=
nullptr
609 ? Capsule->GetComponentLocation() : Walker.GetActorLocation();
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)
619 const UPrimitiveComponent *Component = Overlap.GetComponent();
620 if (Component ==
nullptr)
647 if (result.Key == EActorSpawnResultStatus::Success &&
648 GetWorld()->GetWorldPartition() !=
nullptr)
655 AActor* Actor = result.Value->GetActor();
656 const bool bNeedsGround =
657 Cast<ACarlaWheeledVehicle>(Actor) !=
nullptr ||
658 Cast<AWalkerBase>(Actor) !=
nullptr;
660 !Actor->FindComponentByClass<UWorldPartitionStreamingSourceComponent>())
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;
672 Source->Shapes.Add(Shape);
673 Source->RegisterComponent();
679 UWorldPartitionSubsystem* WPSubsystem =
680 GetWorld()->GetSubsystem<UWorldPartitionSubsystem>();
681 if (WPSubsystem !=
nullptr && !WPSubsystem->IsStreamingCompleted(Source))
683 WPSubsystem->OnUpdateStreamingState();
684 GetWorld()->BlockTillLevelStreamingCompleted();
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);
697 if (
AWalkerBase* Walker = Cast<AWalkerBase>(Actor);
702 UE_LOG(LogCarla, Warning, TEXT(
703 "Walker '%s' spawned inside a building at %s; spawn refused"),
704 *thisActorDescription.
Id, *Actor->GetActorLocation().ToString());
706 return MakeTuple(EActorSpawnResultStatus::Collision,
nullptr);
715 result.Value->GetActorId(),
716 static_cast<uint8_t
>(result.Value->GetActorType()),
724 result.Value->GetActorId(),
725 static_cast<uint8_t
>(result.Value->GetActorType()),
727 std::move(thisActorDescription));
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)
const TArray< FTransform > & GetSpawnPointsTransforms() const
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.
static crp::CityObjectLabel GetTagOfTaggedComponent(const UPrimitiveComponent &Component)
Retrieve the tag of an already tagged component.
ETrafficSignState GetTrafficSignState() const
int32 GetSpeedLimitKmh() const
km/h this sign limits to, -1 when it is not a speed-limit sign.
void Stop(bool KeepActors=false)
A registry of all the Carla actors.
FCarlaActor * FindCarlaActor(IdType Id)
A view over an actor and its properties.
const FActorInfo * GetActorInfo() const
IdType GetActorId() const
std::shared_ptr< carla::multigpu::Router > GetSecondaryServer()
static FOnEpisodeSettingsChange OnEpisodeSettingsChange
void SetEpisode(UCarlaEpisode *ThisEpisode)
void AddEvent(const CarlaRecorderEventAdd &Event)
void CreateRecorderEventAdd(uint32_t DatabaseId, uint8_t Type, const FTransform &Transform, FActorDescription ActorDescription, bool bAddOtherRelatedInfo=true)
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...
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
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.
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>....
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)
static std::optional< road::Map > Load(const std::string &opendrive)
static std::shared_ptr< ROS2 > GetInstance()
std::vector< uint8_t > semantic_tags
ActorDescription description
geom::BoundingBox bounding_box
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.
FString Id
Display ID that identifies the actor.
FActorDescription Description
carla::rpc::Actor SerializedData
float TileStreamingDistance
float ActorActiveDistance
Seting for map generation from opendrive without additional geometry.
bool enable_pedestrian_navigation