7 #include "Engine/WorldComposition.h" 8 #include "Engine/ObjectLibrary.h" 12 #include "Engine/EngineTypes.h" 13 #include "Components/PrimitiveComponent.h" 14 #include "Landscape.h" 15 #include "LandscapeHeightfieldCollisionComponent.h" 16 #include "LandscapeComponent.h" 24 #include "FileHelper.h" 27 #define LARGEMAP_LOGS 1 30 #define LM_LOG(Level, Msg, ...) UE_LOG(LogCarla, Level, TEXT(Msg), ##__VA_ARGS__) 38 PrimaryActorTick.bCanEverTick =
true;
46 FCoreDelegates::PreWorldOriginOffset.RemoveAll(
this);
47 FCoreDelegates::PostWorldOriginOffset.RemoveAll(
this);
49 FWorldDelegates::LevelRemovedFromWorld.RemoveAll(
this);
50 FWorldDelegates::LevelAddedToWorld.RemoveAll(
this);
60 UWorld* World = GetWorld();
70 UWorldComposition* WorldComposition = World->WorldComposition;
71 WorldComposition->bRebaseOriginIn3DSpace =
true;
79 TArray<AActor*> FoundActors;
80 UGameplayStatics::GetAllActorsOfClass(GetWorld(), AActor::StaticClass(), FoundActors);
81 for(
auto CurrentActor : FoundActors)
83 if( CurrentActor->FindComponentByClass( UCustomTerrainPhysicsComponent::StaticClass() ) != nullptr )
91 APlayerController* PlayerController = UGameplayStatics::GetPlayerController(GetWorld(), 0);
94 Spectator = PlayerController->GetPawnOrSpectator();
100 LM_LOG(Log,
"PreWorldOriginOffset Src: %s -> Dst: %s", *InSrcOrigin.ToString(), *InDstOrigin.ToString());
109 UWorld* World = GetWorld();
114 GEngine->AddOnScreenDebugMessage(66,
MsgTime, FColor::Yellow,
115 FString::Printf(TEXT(
"Src: %s -> Dst: %s"), *InSrcOrigin.ToString(), *InDstOrigin.ToString()));
116 LM_LOG(Log,
"PostWorldOriginOffset Src: %s -> Dst: %s", *InSrcOrigin.ToString(), *InDstOrigin.ToString());
119 const TArray<ULevelStreaming*>& StreamingLevels = World->GetStreamingLevels();
120 FColor LevelColor = FColor::White;
121 float MinDistance = 10000000.0f;
122 for (
const auto& TilePair :
MapTiles)
126 FVector LevelLocation = Tile.
Location;
127 float Distance = FVector::Dist(LevelLocation, FVector(InDstOrigin));
128 if (Distance < MinDistance)
130 MinDistance = Distance;
134 #endif // WITH_EDITOR 139 LM_LOG(Warning,
"OnLevelAddedToWorld");
148 LM_LOG(Warning,
"OnLevelRemovedFromWorld");
157 UWorld* World = GetWorld();
160 for (
const auto& CarlaActorPair : ActorRegistry)
162 if (CarlaActorPair.Value->GetActorInfo()->Description.Id ==
"spectator")
174 UWorld* World = GetWorld();
177 bool IsHeroVehicle =
false;
189 if(Attribute && (Attribute->
Value.Contains(
"hero") || Attribute->
Value.Contains(
"ego_vehicle")))
191 LM_LOG(Log,
"HERO VEHICLE DETECTED");
205 World->FlushLevelStreaming();
207 IsHeroVehicle =
true;
225 LM_LOG(Log,
"ACTIVE VEHICLE DETECTED");
233 LM_LOG(Log,
"DORMANT VEHICLE DETECTED");
241 LM_LOG(Warning,
"Actor Spawned at %s", *GlobalPosition.ToString());
259 LM_LOG(Warning,
"ALargeMapManager::OnActorDestroyed %s", *DestroyedActor->GetName());
261 UWorld* World = GetWorld();
319 InTransform.GetRotation(),
321 InTransform.GetScale3D());
332 InTransform.GetRotation(),
334 InTransform.GetScale3D());
346 Super::Tick(DeltaTime);
369 #endif // WITH_EDITOR 380 LM_LOG(Warning,
"Generating Map %s ...", *InAssetsPath);
386 TArray<FAssetData> AssetsData;
387 UObjectLibrary* ObjectLibrary = UObjectLibrary::CreateLibrary(UWorld::StaticClass(),
true,
true);
388 ObjectLibrary->LoadAssetDataFromPath(InAssetsPath);
389 ObjectLibrary->GetAssetDataList(AssetsData);
392 UWorld* World = GetWorld();
394 for (
const FAssetData& AssetData : AssetsData)
400 FString TileName = AssetData.AssetName.ToString();
401 if (!TileName.Contains(
"_Tile_"))
405 FString TileName_X =
"";
406 FString TileName_Y =
"";
407 size_t i = TileName.Len()-1;
409 TCHAR character = TileName[i];
410 if (character ==
'_') {
413 TileName_Y = FString::Chr(character) + TileName_Y;
417 TCHAR character = TileName[i];
418 if (character ==
'_') {
421 TileName_X = FString::Chr(character) + TileName_X;
423 FIntVector TileVectorID = FIntVector(FCString::Atoi(*TileName_X), FCString::Atoi(*TileName_Y), 0);
428 LoadCarlaMapTile(InAssetsPath +
"/" + AssetData.AssetName.ToString(), TileId);
430 ObjectLibrary->ConditionalBeginDestroy();
431 GEngine->ForceGarbageCollection(
true);
440 LM_LOG(Warning,
"GenerateMap num Tiles generated %d",
MapTiles.Num());
442 #endif // WITH_EDITOR 448 LM_LOG(Warning,
"Generating Large Map");
451 for (TPair<FString, FIntVector>& PathId : MapPathsIds)
453 FIntVector& TileVectorID = PathId.Value;
454 FString&
Path = PathId.Key;
460 LM_LOG(Warning,
"GenerateMap num Tiles generated %d",
MapTiles.Num());
461 #endif // WITH_EDITOR 471 UWorld* World = GetWorld();
472 UWorldComposition* WorldComposition = World->WorldComposition;
473 World->ClearStreamingLevels();
474 WorldComposition->TilesStreaming.Empty();
475 WorldComposition->GetTilesList().Empty();
479 ULevelStreamingDynamic* StreamingLevel = It.Value.StreamingLevel;
480 World->AddStreamingLevel(StreamingLevel);
481 WorldComposition->TilesStreaming.Add(StreamingLevel);
500 MinX = (TileID.X < MinX) ? TileID.X : MinX;
501 MaxX = (TileID.X > MaxX) ? TileID.X : MaxX;
503 MinY = (TileID.Y < MinY) ? TileID.Y : MinY;
504 MaxY = (TileID.Y > MaxY) ? TileID.Y : MaxY;
506 return { MaxX - MinX + 1, MaxY - MinY + 1, 0 };
518 LM_LOG(Warning,
"IsLevelOfTileLoaded Tile %s does not exist", *InTileID.ToString());
523 const ULevelStreamingDynamic* StreamingLevel = Tile->
StreamingLevel;
525 return (StreamingLevel && StreamingLevel->GetLoadedLevel());
530 FIntVector VectorId = FIntVector(
540 FIntVector VectorId = (
551 (int32)(TileID >> 32),
552 (int32)(TileID & (int32)(~0)),
565 TileVectorID.Y *= -1;
577 TileVectorID.
Y *= -1;
583 int64 X = ((int64)(TileVectorID.X) << 32);
584 int64 Y = (int64)(TileVectorID.Y) & 0x00000000FFFFFFFF;
612 ULevel* Level = StreamingLevel->GetLoadedLevel();
613 if (Level == InLevel)
643 NewTile.
Name = TileMapPath;
646 FVector TileLocation = NewTile.
Location;
647 FString TileName = NewTile.
Name;
648 UWorld* World = GetWorld();
649 UWorldComposition* WorldComposition = World->WorldComposition;
651 FString FullName = TileMapPath;
652 FString PackageFileName = FullName;
653 FString LongLevelPackageName = FPackageName::FilenameToLongPackageName(PackageFileName);
654 FString UniqueLevelPackageName = LongLevelPackageName;
656 ULevelStreamingDynamic* StreamingLevel = NewObject<ULevelStreamingDynamic>(World, *TileName);
657 check(StreamingLevel);
659 StreamingLevel->SetWorldAssetByPackageName(*UniqueLevelPackageName);
662 if (World->IsPlayInEditor())
664 FWorldContext WorldContext = GEngine->GetWorldContextFromWorldChecked(World);
665 StreamingLevel->RenameForPIE(WorldContext.PIEInstance);
667 StreamingLevel->SetShouldBeVisibleInEditor(
true);
668 StreamingLevel->LevelColor = FColor::MakeRandomColor();
669 #endif // WITH_EDITOR 671 StreamingLevel->SetShouldBeLoaded(
false);
672 StreamingLevel->SetShouldBeVisible(
false);
674 StreamingLevel->bInitiallyLoaded =
false;
675 StreamingLevel->bInitiallyVisible =
false;
676 StreamingLevel->LevelTransform = FTransform(TileLocation);
677 StreamingLevel->PackageNameToLoad = *FullName;
679 if (!FPackageName::DoesPackageExist(FullName, NULL, &PackageFileName))
681 LM_LOG(Error,
"Level does not exist in package with FullName variable -> %s", *FullName);
684 if (!FPackageName::DoesPackageExist(LongLevelPackageName, NULL, &PackageFileName))
686 LM_LOG(Error,
"Level does not exist in package with LongLevelPackageName variable -> %s", *LongLevelPackageName);
690 StreamingLevel->PackageNameToLoad = *LongLevelPackageName;
695 return MapTiles.Add(TileId, NewTile);
701 TSet<TileID> TilesToConsider;
717 TSet<TileID> TilesToBeVisible;
718 TSet<TileID> TilesToHidde;
745 ActorsToRemove.Reset();
752 ActivesToRemove.Reset();
758 DormantsToRemove.Reset();
764 UWorld* World = GetWorld();
773 FVector RelativeLocation = Actor->GetActorLocation();
786 FVector HeroLocation = HeroActor->GetActorLocation();
788 float DistanceSquared = (RelativeLocation - HeroLocation).SizeSquared();
800 LM_LOG(Warning,
"CheckActiveActors Actor does not exist -> Remove actor");
809 UWorld* World = GetWorld();
819 LM_LOG(Warning,
"Converting Active To Dormant... %d", Id);
825 ActiveToDormantActors.Reset();
831 UWorld* World = GetWorld();
842 LM_LOG(Log,
"CheckDormantActors Carla Actor %d not found", Id);
848 LM_LOG(Warning,
"CheckDormantActors IDs doesn't match!! Wanted = %d Received = %d", Id, CarlaActor->
GetActorId());
854 LM_LOG(Warning,
"CheckDormantActors Carla Actor %d is not dormant", Id);
863 FVector HeroLocation =
Actor->GetActorLocation();
868 float DistanceSquared = (RelativeLocation - HeroLocation).SizeSquared();
883 UWorld* World = GetWorld();
888 LM_LOG(Warning,
"Converting %d Dormant To Active", Id);
895 LM_LOG(Warning,
"Spawning dormant at %s\n\tOrigin: %s\n\tRel. location: %s", \
898 *((View->
GetActor()->GetActorLocation()).ToString()) \
904 LM_LOG(Warning,
"Actor %d could not be woken up, keeping sleep state", Id);
908 DormantToActiveActors.Reset();
916 UWorld* World = GetWorld();
917 UWorldComposition* WorldComposition = World->WorldComposition;
922 FVector ActorLocation = ActorToConsider->GetActorLocation();
923 FIntVector ILocation = FIntVector(ActorLocation.X, ActorLocation.Y, ActorLocation.Z);
928 World->SetNewWorldOrigin(FIntVector(NewOrigin));
935 TSet<TileID>& OutTilesToConsider)
938 check(ActorToConsider);
950 for (
int Y = UpperTileId.Y; Y <= LowerTileId.Y; Y++)
952 for (
int X = LowerTileId.X; X <= UpperTileId.X; X++)
956 FIntVector TileToCheck = FIntVector(X, Y, 0);
966 OutTilesToConsider.Add(TileID);
972 const TSet<TileID>& InTilesToConsider,
973 TSet<TileID>& OutTilesToBeVisible,
974 TSet<TileID>& OutTilesToHidde)
982 const TSet<TileID>& InTilesToUpdate,
983 bool InShouldBlockOnLoad,
984 bool InShouldBeLoaded,
985 bool InShouldBeVisible)
988 UWorld* World = GetWorld();
989 UWorldComposition* WorldComposition = World->WorldComposition;
996 ULevelStreamingDynamic* StreamingLevel = CarlaTile->
StreamingLevel;
997 StreamingLevel->bShouldBlockOnLoad = InShouldBlockOnLoad;
998 StreamingLevel->SetShouldBeLoaded(InShouldBeLoaded);
999 StreamingLevel->SetShouldBeVisible(InShouldBeVisible);
1004 const TSet<TileID>& InTilesToBeVisible,
1005 const TSet<TileID>& InTilesToHidde)
1021 int32 X = (int32)(TileID >> 32);
1022 int32 Y = (int32)(TileID);
1023 return FString::Printf(TEXT(
"Tile_%d_%d"), X, Y);
1028 int32 X = (int32)(TileID >> 32);
1029 int32 Y = (int32)(TileID);
1030 return FString::Printf(TEXT(
"%d_%d"), X, Y);
1035 FString FileContent =
"";
1036 FileContent += FString::Printf(TEXT(
"LargeMapManager state\n"));
1038 FileContent += FString::Printf(TEXT(
"Tile:\n"));
1039 FileContent += FString::Printf(TEXT(
"ID\tName\tLocation\n"));
1043 FileContent += FString::Printf(TEXT(
" %ld\t%s\t%s\n"), It.Key, *Tile.
Name, *Tile.
Location.ToString());
1045 FileContent += FString::Printf(TEXT(
"\nNum generated tiles: %d\n"), MapTiles.Num());
1048 TArray<FString> StringArray;
1049 AssetsPath.ParseIntoArray(StringArray, TEXT(
"/"),
false);
1051 FString FilePath = FPaths::ProjectSavedDir() + StringArray[StringArray.Num() - 1] +
".txt";
1052 FFileHelper::SaveStringToFile(
1055 FFileHelper::EEncodingOptions::AutoDetect,
1057 EFileWrite::FILEWRITE_Silent);
1062 UWorld* World = GetWorld();
1068 const TArray<FLevelCollection>& WorldLevelCollections = World->GetLevelCollections();
1069 const FLevelCollection* LevelCollection = World->GetActiveLevelCollection();
1070 const TArray<ULevel*>& Levels = World->GetLevels();
1071 const TArray<ULevelStreaming*>& StreamingLevels = World->GetStreamingLevels();
1072 ULevel* CurrentLevel = World->GetCurrentLevel();
1074 FString Output =
"";
1075 Output += FString::Printf(TEXT(
"Num levels in world composition: %d\n"), World->WorldComposition->TilesStreaming.Num());
1076 Output += FString::Printf(TEXT(
"Num levels loaded: %d\n"), Levels.Num() );
1077 Output += FString::Printf(TEXT(
"Num tiles loaded: %d\n"),
CurrentTilesLoaded.Num() );
1078 Output += FString::Printf(TEXT(
"Tiles loaded: [ "));
1081 Output += FString::Printf(TEXT(
"%s, "), *
TileIDToString(TileId));
1083 Output += FString::Printf(TEXT(
"]\n"));
1084 GEngine->AddOnScreenDebugMessage(0,
MsgTime, FColor::Cyan, Output);
1087 GEngine->AddOnScreenDebugMessage(LastMsgIndex++,
MsgTime, FColor::White,
1088 FString::Printf(TEXT(
"\nActor Global Position: %s km"), *(
FDVector(CurrentActorPosition) / (1000.0 * 100.0)).ToString()) );
1091 GEngine->AddOnScreenDebugMessage(LastMsgIndex++,
MsgTime, FColor::White,
1092 FString::Printf(TEXT(
"\nActor Current Tile: %d_%d"), CurrentTile.X, CurrentTile.Y ));
1095 GEngine->AddOnScreenDebugMessage(LastMsgIndex++,
MsgTime, FColor::White,
1097 GEngine->AddOnScreenDebugMessage(LastMsgIndex++,
MsgTime, FColor::White,
1098 FString::Printf(TEXT(
"Num active actors (%d)"),
ActiveActors.Num()) );
1099 GEngine->AddOnScreenDebugMessage(LastMsgIndex++,
MsgTime, FColor::White,
1100 FString::Printf(TEXT(
"Num dormant actors (%d)"),
DormantActors.Num()));
1101 GEngine->AddOnScreenDebugMessage(LastMsgIndex++,
MsgTime, FColor::White,
1108 float ToKm = 1000.0f * 100.0f;
1109 FVector TileActorLocation =
Actor->GetActorLocation();
1112 Output += FString::Printf(TEXT(
"Local Loc: %s meters\n"), *(TileActorLocation / ToKm).ToString());
1113 Output += FString::Printf(TEXT(
"Client Loc: %s km\n"), *(ClientActorLocation / ToKm).ToString());
1114 Output +=
"---------------";
FCarlaActor * FindCarlaActor(FCarlaActor::IdType ActorId)
Find a Carla actor by id.
TileID GetTileID(FVector TileLocation) const
From a given location it retrieves the TileID that covers that area.
TSet< uint64 > CurrentTilesLoaded
FString GenerateTileName(TileID TileID)
void UpdateCurrentTilesLoaded(const TSet< TileID > &InTilesToBeVisible, const TSet< TileID > &InTilesToHidde)
A registry of all the Carla actors.
void GenerateMap(FString InAssetsPath)
TSet< FCarlaActor::IdType > DormantsToRemove
TSet< FCarlaActor::IdType > DormantToActiveActors
bool ShouldTilesBlockOnLoad
void ConvertActiveToDormantActors()
FIntVector GetNumTilesInXY() const
float LayerStreamingDistance
void ConsiderSpectatorAsEgo(bool _SpectatorAsEgo)
FVector GlobalToLocalLocation(const FVector &InLocation) const
void ConvertDormantToActiveActors()
float LayerStreamingDistanceSquared
ACarlaWheeledVehicle * GetHeroVehicle()
void WakeActorUp(carla::rpc::ActorId ActorId)
std::vector< cg::Location > Path
void RegisterTilesInWorldComposition()
TSet< FCarlaActor::IdType > ActiveToDormantActors
const int32 TilesDistMsgIndex
FCarlaMapTile & LoadCarlaMapTile(FString TileMapPath, TileID TileId)
FString TileIDToString(TileID TileID)
bool IsLevelOfTileLoaded(FIntVector InTileID) const
static bool IsValid(const ACarlaWheeledVehicle *Vehicle)
float ActorStreamingDistance
void PutActorToSleep(carla::rpc::ActorId ActorId)
void OnActorSpawned(const FCarlaActor &CarlaActor)
FIntVector CurrentOriginInt
static T Get(carla::rpc::Response< T > &response)
void UpdateTileState(const TSet< TileID > &InTilesToUpdate, bool InShouldBlockOnLoad, bool InShouldBeLoaded, bool InShouldBeVisible)
virtual void BeginPlay() override
float ActorStreamingDistanceSquared
FVector ToFVector() const
static void TagActorsInLevel(UWorld &World, bool bTagForSemanticSegmentation)
Set the tag of every actor in level.
const FActorRegistry & GetActorRegistry() const
TMap< FString, FActorAttribute > Variations
User selected variations of the actor.
FActorData * GetActorData()
carla::SharedPtr< cc::Actor > Actor
void ClearWorldAndTiles()
void GetTilesThatNeedToChangeState(const TSet< TileID > &InTilesToConsider, TSet< TileID > &OutTilesToBeVisible, TSet< TileID > &OutTilesToHidde)
float tick_execution_time
const int32 ClientLocMsgIndex
void SetActorStreamingDistance(float Distance)
void PreWorldOriginOffset(UWorld *InWorld, FIntVector InSrcOrigin, FIntVector InDstOrigin)
void SetTileSize(float Size)
void DumpTilesTable() const
void RegisterInitialObjects()
A description of a Carla Actor with all its variation.
FActorDescription Description
const FActorInfo * GetActorInfo() const
TMap< uint64, FCarlaMapTile > MapTiles
void CheckIfRebaseIsNeeded()
void SetLayerStreamingDistance(float Distance)
void SetCurrentMapOrigin(const FIntVector &NewOrigin)
void GetTilesToConsider(const AActor *ActorToConsider, TSet< TileID > &OutTilesToConsider)
FDVector GetTileLocationD(TileID TileID) const
FTransform LocalToGlobalTransform(const FTransform &InTransform) const
TArray< AActor * > ActorsToConsider
void AddActorToUnloadedList(const FCarlaActor &CarlaActor, const FTransform &Transform)
#define LM_LOG(Level, Msg,...)
float GetActorStreamingDistance() const
float GetLayerStreamingDistance() const
FTransform GlobalToLocalTransform(const FTransform &InTransform) const
void PostWorldOriginOffset(UWorld *InWorld, FIntVector InSrcOrigin, FIntVector InDstOrigin)
static UCarlaEpisode * GetCurrentEpisode(const UObject *WorldContextObject)
void OnLevelRemovedFromWorld(ULevel *InLevel, UWorld *InWorld)
FCarlaMapTile * GetCarlaMapTile(FVector Location)
A view over an actor and its properties.
TSet< FCarlaActor::IdType > ActivesToRemove
TSet< AActor * > ActorsToRemove
float RebaseOriginDistance
const int32 MaxClientLocMsgIndex
IdType GetActorId() const
ULevelStreamingDynamic * StreamingLevel
void RemovePendingActorsToRemove()
void SetTile0Offset(const FVector &Offset)
TArray< FCarlaActor::IdType > ActiveActors
Base class for CARLA wheeled vehicles.
void OnActorDestroyed(AActor *DestroyedActor)
An actor attribute, may be an intrinsic (non-modifiable) attribute of the actor or an user-defined ac...
void Tick(float DeltaTime) override
float RebaseOriginDistanceSquared
FVector GetTileLocation(TileID TileID) const
geom::Transform Transform
FVector LocalToGlobalLocation(const FVector &InLocation) const
bool IsTileLoaded(TileID TileId) const
void CheckDormantActors()
ActorType GetActorType() const
FIntVector GetTileVectorID(FVector TileLocation) const
A view over an actor and its properties.
TArray< FCarlaActor::IdType > DormantActors
void OnLevelAddedToWorld(ULevel *InLevel, UWorld *InWorld)