13#include "Engine/DecalActor.h"
14#include "Engine/LevelStreaming.h"
15#include "Engine/LocalPlayer.h"
16#include "Materials/MaterialInstanceDynamic.h"
17#include "Engine/StaticMeshActor.h"
20#include "EngineUtils.h"
30#include "Async/ParallelFor.h"
31#include "DynamicRHI.h"
33#include "DrawDebugHelpers.h"
34#include "Kismet/KismetSystemLibrary.h"
41 : Super(ObjectInitializer)
43 PrimaryActorTick.bCanEverTick =
true;
44 PrimaryActorTick.TickGroup = TG_PrePhysics;
45 bAllowTickBeforeBeginPlay =
false;
47 Episode = CreateDefaultSubobject<UCarlaEpisode>(TEXT(
"Episode"));
49 Recorder = CreateDefaultSubobject<ACarlaRecorder>(TEXT(
"Recorder"));
51 ObjectRegister = CreateDefaultSubobject<UObjectRegister>(TEXT(
"ObjectRegister"));
54 HUDClass = ACarlaHUD::StaticClass();
56 TaggerDelegate = CreateDefaultSubobject<UTaggerDelegate>(TEXT(
"TaggerDelegate"));
57 CarlaSettingsDelegate = CreateDefaultSubobject<UCarlaSettingsDelegate>(TEXT(
"CarlaSettingsDelegate"));
62 UWorld*
World = GetWorld();
63 TSoftObjectPtr<UWorld> AssetPtr (
World);
64 FString Path = FPaths::GetPath(AssetPtr.GetLongPackageName());
65 Path.RemoveFromStart(
"/Game/");
74 return FPaths::ConvertRelativePathToFull(FPaths::ProjectContentDir()) + Path;
78 const FString &MapName,
79 const FString &Options,
80 FString &ErrorMessage)
83 Super::InitGame(MapName, Options, ErrorMessage);
85 UWorld*
World = GetWorld();
86 check(
World !=
nullptr);
87 FString InMapName(MapName);
91 TEXT(
"Missing episode, can't continue without an episode!"));
94 UGameplayStatics::GetActorOfClass(GetWorld(), ALargeMapManager::StaticClass());
95 LMManager = Cast<ALargeMapManager>(LMManagerActor);
108 FString CorrectedMapName = InMapName;
109 constexpr auto PIEPrefix = TEXT(
"UEDPIE_0_");
110 CorrectedMapName.RemoveFromStart(PIEPrefix);
111 UE_LOG(LogCarla, Log, TEXT(
"Corrected map name from %s to %s"), *InMapName, *CorrectedMapName);
112 Episode->MapName = CorrectedMapName;
118 GameInstance = Cast<UCarlaGameInstance>(GetGameInstance());
121 TEXT(
"GameInstance is not a UCarlaGameInstance, did you forget to set "
122 "it in the project settings?"));
127 UE_LOG(LogCarla, Error, TEXT(
"Missing TaggerDelegate!"));
134 UE_LOG(LogCarla, Error, TEXT(
"Missing CarlaSettingsDelegate!"));
138 UGameplayStatics::GetActorOfClass(GetWorld(), AWeather::StaticClass());
139 if (WeatherActor !=
nullptr) {
140 UE_LOG(LogCarla, Log, TEXT(
"Existing weather actor. Doing nothing then!"));
146 UE_LOG(LogCarla, Error, TEXT(
"Missing weather class!"));
176 Super::RestartPlayer(NewPlayer);
183 UWorld*
World = GetWorld();
184 check(
World !=
nullptr);
201 World->SpawnActor<ADecalActor>(
202 FVector(0,0,-1000000), FRotator(0,0,0), FActorSpawnParameters());
205 Manager->InitializeTrafficLights();
207 Episode->InitializeAtBeginPlay();
210 if (
Episode->Weather !=
nullptr)
233 TArray<AActor*> FoundActors;
234 UGameplayStatics::GetAllActorsOfClass(
World, AActor::StaticClass(), FoundActors);
237 TArray<UCarlaLight*> Lights;
238 Actor->GetComponents(Lights,
false);
239 for(UCarlaLight* Light : Lights)
241 Light->RegisterLight();
249 TArray<FString> Names;
251 UGameplayStatics::GetAllActorsOfClass(GetWorld(), AActor::StaticClass(),
Actors);
254 TArray<UStaticMeshComponent*> StaticMeshes;
255 Actor->GetComponents(StaticMeshes);
256 if (StaticMeshes.Num())
258 Names.Add(
Actor->GetName());
267 UGameplayStatics::GetAllActorsOfClass(GetWorld(), AActor::StaticClass(),
Actors);
270 if(
Actor->GetName() == ActorName)
281 FlushRenderingCommands();
282 TArray<FColor> Colors;
283 for (uint32_t y = 0; y < Texture.
GetHeight(); y++)
285 for (uint32_t x = 0; x < Texture.
GetWidth(); x++)
287 auto& Color = Texture.
At(x,y);
288 Colors.Add(FColor(Color.r, Color.g, Color.b, Color.a));
291 UTexture2D* UETexture = UTexture2D::CreateTransient(Texture.
GetWidth(), Texture.
GetHeight(), EPixelFormat::PF_B8G8R8A8);
292 FTexture2DMipMap& Mip = UETexture->PlatformData->Mips[0];
293 void* Data = Mip.BulkData.Lock( LOCK_READ_WRITE );
294 FMemory::Memcpy( Data,
297 Mip.BulkData.Unlock();
298 UETexture->UpdateResource();
304 FlushRenderingCommands();
305 TArray<FFloat16Color> Colors;
306 for (uint32_t y = 0; y < Texture.
GetHeight(); y++)
308 for (uint32_t x = 0; x < Texture.
GetWidth(); x++)
310 auto& Color = Texture.
At(x,y);
311 Colors.Add(FLinearColor(Color.r, Color.g, Color.b, Color.a));
314 UTexture2D* UETexture = UTexture2D::CreateTransient(Texture.
GetWidth(), Texture.
GetHeight(), EPixelFormat::PF_FloatRGBA);
315 FTexture2DMipMap& Mip = UETexture->PlatformData->Mips[0];
316 void* Data = Mip.BulkData.Lock( LOCK_READ_WRITE );
317 FMemory::Memcpy( Data,
320 Mip.BulkData.Unlock();
321 UETexture->UpdateResource();
331 TArray<UStaticMeshComponent*> StaticMeshes;
332 Actor->GetComponents(StaticMeshes);
333 for (UStaticMeshComponent* Mesh : StaticMeshes)
335 for (
int i = 0; i < Mesh->GetNumMaterials(); ++i)
337 UMaterialInterface* OriginalMaterial = Mesh->GetMaterial(i);
338 UMaterialInstanceDynamic* DynamicMaterial = Cast<UMaterialInstanceDynamic>(OriginalMaterial);
341 DynamicMaterial = UMaterialInstanceDynamic::Create(OriginalMaterial, NULL);
342 Mesh->SetMaterial(i, DynamicMaterial);
347 case cr::MaterialParameter::Tex_Diffuse:
348 DynamicMaterial->SetTextureParameterValue(
"BaseColor", Texture);
349 DynamicMaterial->SetTextureParameterValue(
"Difuse", Texture);
350 DynamicMaterial->SetTextureParameterValue(
"Difuse 2", Texture);
351 DynamicMaterial->SetTextureParameterValue(
"Difuse 3", Texture);
352 DynamicMaterial->SetTextureParameterValue(
"Difuse 4", Texture);
354 case cr::MaterialParameter::Tex_Normal:
355 DynamicMaterial->SetTextureParameterValue(
"Normal", Texture);
356 DynamicMaterial->SetTextureParameterValue(
"Normal 2", Texture);
357 DynamicMaterial->SetTextureParameterValue(
"Normal 3", Texture);
358 DynamicMaterial->SetTextureParameterValue(
"Normal 4", Texture);
360 case cr::MaterialParameter::Tex_Emissive:
361 DynamicMaterial->SetTextureParameterValue(
"Emissive", Texture);
363 case cr::MaterialParameter::Tex_Ao_Roughness_Metallic_Emissive:
364 DynamicMaterial->SetTextureParameterValue(
"AO / Roughness / Metallic / Emissive", Texture);
365 DynamicMaterial->SetTextureParameterValue(
"ORMH", Texture);
366 DynamicMaterial->SetTextureParameterValue(
"ORMH 2", Texture);
367 DynamicMaterial->SetTextureParameterValue(
"ORMH 3", Texture);
368 DynamicMaterial->SetTextureParameterValue(
"ORMH 4", Texture);
377 Super::Tick(DeltaSeconds);
393 Super::EndPlay(EndPlayReason);
403 auto *
World = GetWorld();
404 check(
World !=
nullptr);
408 if (FactoryClass !=
nullptr)
411 if (Factory !=
nullptr)
413 Episode->RegisterActorFactory(*Factory);
418 UE_LOG(LogCarla, Error, TEXT(
"Failed to spawn actor spawner"));
426 for (TActorIterator<AVehicleSpawnPoint> It(GetWorld()); It; ++It)
442 UE_LOG(LogCarla, Log, TEXT(
"Generating SpawnPoints ..."));
444 std::vector<std::pair<carla::road::element::Waypoint, carla::road::element::Waypoint>> Topology =
Map->GenerateTopology();
446 UWorld*
World = GetWorld();
448 for(
auto& Pair : Topology)
451 FTransform Transform(CarlaTransform);
454 Transform.AddToTranslation(FVector(0.f, 0.f, 50.0f));
467 if (!
Map.has_value()) {
468 UE_LOG(LogCarla, Error, TEXT(
"Invalid Map"));
472 Episode->MapGeoReference =
Map->GetGeoReference();
480 UWorld*
World = GetWorld();
481 AActor* TrafficLightManagerActor = UGameplayStatics::GetActorOfClass(
World, ATrafficLightManager::StaticClass());
482 if(TrafficLightManagerActor ==
nullptr)
484 FActorSpawnParameters SpawnParams;
499 TArray<AActor*> WorldActors;
500 UGameplayStatics::GetAllActorsOfClass(GetWorld(), AStaticMeshActor::StaticClass(), WorldActors);
504 AStaticMeshActor *MeshActor = CastChecked<AStaticMeshActor>(
Actor);
507 if (MeshActor->GetStaticMeshComponent()->GetStaticMesh() == NULL)
509 UE_LOG(LogTemp, Error, TEXT(
"The object : %s has no mesh"), *MeshActor->GetFullName());
518 TArray<AActor*> WorldActors;
519 UGameplayStatics::GetAllActorsOfClass(GetWorld(), AStaticMeshActor::StaticClass(), WorldActors);
523 AStaticMeshActor *MeshActor = CastChecked<AStaticMeshActor>(
Actor);
524 if(MeshActor->GetStaticMeshComponent()->GetStaticMesh() != NULL)
528 if (MeshTag != crp::CityObjectLabel::Roads &&
529 MeshTag != crp::CityObjectLabel::Sidewalks &&
530 MeshTag != crp::CityObjectLabel::RoadLines &&
531 MeshTag != crp::CityObjectLabel::Ground &&
532 MeshTag != crp::CityObjectLabel::Terrain &&
533 MeshActor->GetStaticMeshComponent()->GetGenerateOverlapEvents() ==
false)
535 MeshActor->GetStaticMeshComponent()->SetGenerateOverlapEvents(
true);
544 auto World = GetWorld();
545 check(
World !=
nullptr);
554 UKismetSystemLibrary::FlushDebugStrings(
World);
555 UKismetSystemLibrary::FlushPersistentDebugLines(
World);
560 const auto& Signals =
Map->GetSignals();
561 const auto& Controllers =
Map->GetControllers();
563 for(
const auto& Signal : Signals) {
564 const auto& ODSignal = Signal.second;
565 const FTransform Transform = ODSignal->GetTransform();
566 const FVector Location = Transform.GetLocation();
567 const FQuat Rotation = Transform.GetRotation();
579 TArray<const cre::RoadInfoSignal*> References;
580 auto waypoints =
Map->GenerateWaypointsOnRoadEntries();
581 std::unordered_set<cr::RoadId> ExploredRoads;
582 for (
auto & waypoint : waypoints)
585 if (ExploredRoads.count(waypoint.road_id) > 0)
589 ExploredRoads.insert(waypoint.road_id);
592 auto SignalReferences =
Map->GetLane(waypoint).
594 for (
auto *SignalReference : SignalReferences)
596 References.Add(SignalReference);
599 for (
auto& Reference : References)
601 auto RoadId = Reference->GetRoadId();
602 const auto* SignalReference = Reference;
603 const FTransform SignalTransform = SignalReference->GetSignal()->GetTransform();
604 for(
auto &validity : SignalReference->GetValidities())
611 auto signal_waypoint =
Map->GetWaypoint(
612 RoadId, lane, SignalReference->GetS()).get();
614 if(
Map->GetLane(signal_waypoint).GetType() != cr::Lane::LaneType::Driving)
617 FTransform ReferenceTransform =
Map->ComputeTransform(signal_waypoint);
621 ReferenceTransform.GetLocation(),
630 ReferenceTransform.GetLocation(),
631 SignalTransform.GetLocation(),
643 UWorld*
World = GetWorld();
646 TArray<AActor*> FoundActors;
647 UGameplayStatics::GetAllActorsOfClass(
World, AActor::StaticClass(), FoundActors);
649 TArray<FBoundingBox> BoundingBoxes;
652 return BoundingBoxes;
658 TArray<AActor*> FoundActors;
659 UGameplayStatics::GetAllActorsOfClass(GetWorld(), AActor::StaticClass(), FoundActors);
664 const TSet<uint64>& EnvObjectIds,
672 const UWorld*
World = GetWorld();
673 UGameplayStatics::FlushLevelStreaming(
World);
675 TArray<FName> LevelsToLoad;
678 FLatentActionInfo LatentInfo;
679 LatentInfo.CallbackTarget =
this;
680 LatentInfo.ExecutionFunction =
"OnLoadStreamLevel";
681 LatentInfo.Linkage = 0;
686 for(FName& LevelName : LevelsToLoad)
689 UGameplayStatics::LoadStreamLevel(
World, LevelName,
true,
true, LatentInfo);
691 UGameplayStatics::FlushLevelStreaming(
World);
697 const UWorld*
World = GetWorld();
699 TArray<FName> LevelsToUnLoad;
702 FLatentActionInfo LatentInfo;
703 LatentInfo.CallbackTarget =
this;
704 LatentInfo.ExecutionFunction =
"OnUnloadStreamLevel";
706 LatentInfo.Linkage = 0;
710 for(FName& LevelName : LevelsToUnLoad)
713 UGameplayStatics::UnloadStreamLevel(
World, LevelName, LatentInfo,
false);
715 UGameplayStatics::FlushLevelStreaming(
World);
722 UWorld*
World = GetWorld();
723 const TArray <ULevelStreaming*> Levels =
World->GetStreamingLevels();
724 TArray<FString> LayersToLoad;
733 FString LayerName = UTF8_TO_TCHAR(MapLayerToString(
static_cast<crp::MapLayer>(LayerMask)).c_str());
737 LayersToLoad.Emplace(LayerName);
739 LayerMask = (LayerMask << 1) & AllLayersMask;
743 for(ULevelStreaming* Level : Levels)
745 TArray<FString> StringArray;
746 FString FullSubMapName = Level->GetWorldAssetPackageFName().ToString();
748 FullSubMapName.ParseIntoArray(StringArray, TEXT(
"/"),
false);
749 FString SubMapName = StringArray[StringArray.Num() - 1];
750 for(FString LayerName : LayersToLoad)
752 if(SubMapName.Contains(LayerName))
754 OutLevelNames.Emplace(FName(*SubMapName));
764 ULevel* OutLevel =
nullptr;
765 UWorld*
World = GetWorld();
766 const TArray <ULevelStreaming*> Levels =
World->GetStreamingLevels();
768 for(ULevelStreaming* Level : Levels)
770 FString FullSubMapName = Level->GetWorldAssetPackageFName().ToString();
771 if(FullSubMapName.Contains(LevelName))
773 OutLevel = Level->GetLoadedLevel();
776 UE_LOG(LogCarla, Warning, TEXT(
"%s has not been loaded"), *LevelName);
UE_LOG(LogCarla, Log, TEXT("UActorDispatcher::Destroying actor: '%s' %x"), *Id, Actor)
TMap< IdType, AActor * > Actors
TSharedPtr< const FActorInfo > carla::rpc::ActorState UWorld * World
TSharedPtr< const FActorInfo > carla::rpc::ActorState UWorld Actor
TSubclassOf< AWeather > WeatherClass
要生成的 Weather 类。
void RegisterEnvironmentObjects()
void UnLoadMapLayer(int32 MapLayers)
TArray< FTransform > SpawnPointsTransforms
void EnableEnvironmentObjects(const TSet< uint64 > &EnvObjectIds, bool Enable)
TArray< ACarlaActorFactory * > ActorFactoryInstances
void DebugShowSignals(bool enable)
void BeginPlay() override
UCarlaGameInstance * GameInstance
UCarlaSettingsDelegate * CarlaSettingsDelegate
int32 LatentInfoUUID
在同一个即时报价中
AActor * FindActorByName(const FString &ActorName)
void LoadMapLayer(int32 MapLayers)
void InitGame(const FString &MapName, const FString &Options, FString &ErrorMessage) override
void CheckForEmptyMeshes()
void ApplyTextureToActor(AActor *Actor, UTexture2D *Texture, const carla::rpc::MaterialParameter &TextureParam)
const FString GetFullMapPath() const
ALargeMapManager * LMManager
void RestartPlayer(AController *NewPlayer) override
void SpawnActorFactories()
ACarlaRecorder * Recorder
void EnableOverlapEvents()
void EndPlay(const EEndPlayReason::Type EndPlayReason) override
ULevel * GetULevelFromName(FString LevelName)
FDelegateHandle OnEpisodeSettingsChangeHandle
const FString GetRelativeMapPath() const
void ConvertMapLayerMaskToMapNames(int32 MapLayer, TArray< FName > &OutLevelNames)
void GenerateSpawnPoints()
int PendingLevelsToUnLoad
UTaggerDelegate * TaggerDelegate
ATrafficLightManager * TrafficLightManager
UObjectRegister * ObjectRegister
void OnEpisodeSettingsChanged(const FEpisodeSettings &Settings)
ATrafficLightManager * GetTrafficLightManager()
TArray< FString > GetNamesOfAllActors()
void Tick(float DeltaSeconds) override
TArray< FBoundingBox > GetAllBBsOfLevel(uint8 TagQueried=0xFF) const
ACarlaGameModeBase(const FObjectInitializer &ObjectInitializer)
TSet< TSubclassOf< ACarlaActorFactory > > ActorFactories
将用于定义和生成 actor 的 actor 生成器列表 在游戏中可用。
void OnUnloadStreamLevel()
bool ReadyToRegisterObjects
UTexture2D * CreateUETexture(const carla::rpc::TextureColor &Texture)
CarlaReplayer * GetReplayer(void)
void SetEpisode(UCarlaEpisode *ThisEpisode)
void RegisterInitialObjects()
void ConsiderSpectatorAsEgo(bool _SpectatorAsEgo)
static crp::CityObjectLabel GetTagOfTaggedComponent(const UPrimitiveComponent &Component)
检索已标记组件的标记。
static void TagActorsInLevel(UWorld &World, bool bTagForSemanticSegmentation)
设置 level 中每个 actor 的标签。
FWeatherParameters Weather
void CheckPlayAfterMapLoaded(void)
static FOnEpisodeSettingsChange OnEpisodeSettingsChange
地图类的前向声明,用于在LaneInvasionSensor类中可能的引用。
static TArray< FBoundingBox > GetBoundingBoxOfActors(const TArray< AActor * > &Actors, uint8 InTagQueried=0xFF)
void NotifyBeginEpisode(UCarlaEpisode &Episode)
int32 GetCurrentMapLayer() const
void ApplyQualityLevelPreRestart()
加载关卡之前,应用当前设置
void ApplyQualityLevelPostRestart()
加载关卡后,应用当前设置
void SetAllActorsDrawDistance(UWorld *world, float max_draw_distance) const
void RegisterSpawnHandler(UWorld *World)
在此处为所有新生成的参与者创建事件触发器处理程序,以便使用自定义函数进行处理。
void EnableEnvironmentObjects(const TSet< uint64 > &EnvObjectIds, bool Enable)
void RegisterObjects(TArray< AActor * > Actors)
static FString GetXODR(const UWorld *World)
MapNameOpenDrive XMLҲļؿա
void SetSemanticSegmentationEnabled(bool Enable=true)
void RegisterSpawnHandler(UWorld *World)
static std::vector< int > GenerateRange(int a, int b)
Vector3D GetUpVector() const
static boost::optional< road::Map > Load(const std::string &opendrive)
T & At(uint32_t x, uint32_t y)
uint32_t GetWidth() const
uint32_t GetHeight() const
static WeatherParameters Default