Agrarsense
Tagger.cpp
Go to the documentation of this file.
1// Copyright (c) 2023 FrostBit Software Lab at the Lapland University of Applied Sciences
2//
3// This work is licensed under the terms of the MIT license.
4// For a copy, see <https://opensource.org/licenses/MIT>.
5
6#include "Tagger.h"
12
14#include "GeoReferencingSystem.h"
15#include "AssetRegistry/AssetRegistryModule.h"
16#include "Components/SkeletalMeshComponent.h"
17#include "Components/StaticMeshComponent.h"
18#include "Engine/SkeletalMesh.h"
19#include "Engine/StaticMesh.h"
20#include "Landscape.h"
21#include "LandscapeComponent.h"
22#include "Engine/World.h"
23#include "Kismet/GameplayStatics.h"
24#include "TimerManager.h"
25
27{
28 PrimaryActorTick.bCanEverTick = false;
29}
30
32{
33 Super::BeginPlay();
34
36 {
37 return;
38 }
39
40 UWorld* World = GetWorld();
41
42 // Create TMap<FString, ELabels>
43 LabelMap = UEnumUtilities::CreateStringEnumMap<ELabels>("/Script/Agrarsense.ELabels");
44
45 ActorSpawnedDelegateHandle = World->AddOnActorSpawnedHandler(FOnActorSpawned::FDelegate::CreateUObject(this, &ATagger::OnActorSpawned));
46
47 // Tag all existing Actors in the World after small delay
48 FTimerHandle Handle;
49 World->GetTimerManager().SetTimer(Handle, FTimerDelegate::CreateLambda([this]
50 {
52 }), 0.200f, false);
53}
54
55void ATagger::EndPlay(const EEndPlayReason::Type EndPlayReason)
56{
57 Super::EndPlay(EndPlayReason);
58
59 TaggedActors.Empty();
61}
62
64{
65 TArray<AActor*> Actors;
66 UGameplayStatics::GetAllActorsOfClass(GetWorld(), AActor::StaticClass(), Actors);
67
68 TaggedActors.Reserve(Actors.Num());
69
70 // Sort actors based on distance to the origin (0,0,0)
71 // This way we can ensure that the actors are tagged in a consistent order each run
72 const FVector Origin(0.0f, 0.0f, 0.0f);
73 Actors.Sort([&](const AActor& A, const AActor& B)
74 {
75 return FVector::DistSquared(A.GetActorLocation(), Origin) < FVector::DistSquared(B.GetActorLocation(), Origin);
76 });
77
78 for (AActor* Actor : Actors)
79 {
80 if (Actor)
81 {
82 TagActor(*Actor);
83 }
84 }
85}
86
87void ATagger::OnActorSpawned(AActor* Actor)
88{
89 if (Actor)
90 {
91 TagActor(*Actor);
92 }
93}
94
95template <typename T>
96static auto CastEnum(T label)
97{
98 return static_cast<typename std::underlying_type<T>::type>(label);
99}
100
101void ATagger::TagActor(AActor& Actor)
102{
103//#ifndef InstanceSegmentationPass_EXISTS
104// AInstancedActor* InstancedActor = Cast<AInstancedActor>(&Actor);
105// if (InstancedActor)
106// {
107// if (InstancedActor->IsCustomDepthSetup())
108// {
109// // Custom depth has been setup beforehand. Return
110// return;
111// }
112// }
113//
114// AWalker* Walker = Cast<AWalker>(&Actor);
115// if (Walker)
116// {
117// // If the actor is AWalker, return. These are tagged in editor.
118// return;
119// }
120//#endif
121
122 // Check if this is a Landscape actor
123 // if so, apply same ID and label to all landscape and its components.
124 ALandscape* Landscape = Cast<ALandscape>(&Actor);
125 if (Landscape)
126 {
127 TagLandscape(Landscape, Actor);
128 return;
129 }
130
131 // Iterate all static meshes
132 TArray<UStaticMeshComponent*> StaticMeshComponents;
133 Actor.GetComponents<UStaticMeshComponent>(StaticMeshComponents);
134 for (UStaticMeshComponent* Component : StaticMeshComponents)
135 {
136 if (Component)
137 {
138 ELabels Label = GetLabelFromStaticComponent(Component);
139 float InstanceSegmentationID = SetStencilValue(*Component, Actor, Label);
140
141 FTaggedActorData ActorData;
142 ActorData.Actor = &Actor;
143 ActorData.InstanceID = InstanceSegmentationID;
144 ActorData.StaticMeshComponent = Component;
145 ActorData.Label = Label;
146 TaggedActors.Add(ActorData);
147 }
148 }
149
150 // Iterate all skeletal meshes
151 TArray<USkeletalMeshComponent*> SkeletalMeshComponents;
152 Actor.GetComponents<USkeletalMeshComponent>(SkeletalMeshComponents);
153 for (USkeletalMeshComponent* Component : SkeletalMeshComponents)
154 {
155 if (Component)
156 {
158 float InstanceSegmentationID = SetStencilValue(*Component, Actor, Label);
159
160 FTaggedActorData ActorData;
161 ActorData.Actor = &Actor;
162 ActorData.InstanceID = InstanceSegmentationID;
163 ActorData.SkeletalMeshComponent = Component;
164 ActorData.Label = Label;
165 TaggedActors.Add(ActorData);
166 }
167 }
168}
169
170float ATagger::SetStencilValue(UPrimitiveComponent& Component, AActor& Actor, const ELabels& Label)
171{
172 Component.SetRenderCustomDepth(true);
173
174 const int32 ActorLabelStencilValue = static_cast<int32>(Label) + 1;
175 float ActorLabelStencilValueFloat = static_cast<float>(ActorLabelStencilValue);
176
177#if ENGINE_MAJOR_VERSION < 5 || (ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION <= 5)
178 ActorLabelStencilValueFloat = static_cast<float>(ActorLabelStencilValue - 1);
179#endif
180
181 Component.SetCustomDepthStencilValue(ActorLabelStencilValue);
182
183 float CurrentID = ID;
184
185 // Set custom primitive data, used for instance segmentation.
186 Component.SetCustomPrimitiveDataVector4(4,
187 FVector4(CurrentID,
188 ActorLabelStencilValueFloat,
189 0.0f,
190 0.0f));
191
192 // Increase ID counter
193 ID += 1.0f;
194
195 return CurrentID;
196}
197
199{
200 if (TaggedActors.IsEmpty())
201 {
202 return;
203 }
204
206 if (!CSVFile)
207 {
208 return;
209 }
210
211 for (const FTaggedActorData& TaggedActorData : TaggedActors)
212 {
213 AActor* Actor = TaggedActorData.Actor;
214 if (!Actor)
215 {
216 continue;
217 }
218
219 WriteComponentToCSV(TaggedActorData);
220 }
221
222 CSVFile->Close();
223}
224
225AActor* ATagger::GetActorByInstanceID(float InstanceID)
226{
227 for (const FTaggedActorData& TaggedActorData : TaggedActors)
228 {
229 if (TaggedActorData.InstanceID == InstanceID)
230 {
231 return TaggedActorData.Actor;
232 }
233 }
234
235 return nullptr;
236}
237
239{
240 GeoReferencingSystem = AGeoReferencingSystem::GetGeoReferencingSystem(GetWorld());
241
242 // CSV file settings
243 FCSVFileSettings Settings;
245 Settings.Append = false;
246 Settings.CreateUnique = true;
248
249 FString MapName = GetWorld()->GetMapName();
250 FString FileName = MapName + TEXT("_ObjectLocations");
251
252 if (MapName.Contains("dev"))
253 {
254 Settings.QueueSize = 65536;
255 }
256
257 CSVFile = UCSVFile::CreateCSVFile(FileName, Settings);
258
259 TArray<FString> Header = { TEXT("Name"), TEXT("InstanceID"), TEXT("LocationX"), TEXT("LocationY"),
260 TEXT("LocationZ"), TEXT("Yaw"), TEXT("Pitch"), TEXT("Roll"), TEXT("Bounds")};
262 {
263 Header.Append({ TEXT("Latitude"), TEXT("Longitude"), TEXT("Altitude") });
264 }
265 CSVFile->WriteRow(Header);
266}
267
269{
270 AActor* Actor = Data.Actor;
271
272 if (!Actor)
273 {
274 return;
275 }
276
277 FString AssetPath;
278 FString MeshName;
279 FVector Location = Actor->GetActorLocation();
280 FRotator Rotation = Actor->GetActorRotation();
281 FBoxSphereBounds Bounds;
282
283 // Try StaticMeshComponent first
284 if (Data.StaticMeshComponent && Data.StaticMeshComponent->GetStaticMesh())
285 {
286 UStaticMesh* StaticMesh = Data.StaticMeshComponent->GetStaticMesh();
287 AssetPath = StaticMesh->GetPathName();
288 MeshName = StaticMesh->GetName();
289 Bounds = StaticMesh->GetBounds();
290 }
291 // If not valid, try SkeletalMeshComponent
292 else if (Data.SkeletalMeshComponent && Data.SkeletalMeshComponent->GetSkeletalMeshAsset())
293 {
294 USkeletalMesh* SkeletalMesh = Data.SkeletalMeshComponent->GetSkeletalMeshAsset();
295 AssetPath = SkeletalMesh->GetPathName();
296 MeshName = SkeletalMesh->GetName();
297 Bounds = SkeletalMesh->GetBounds();
298 }
299 else
300 {
301 return;
302 }
303
304 // Check asset path
305 if (!AssetPath.StartsWith(TEXT("/Game/Agrarsense/Models")))
306 {
307 return;
308 }
309
310 TArray<FString> Row;
311 Row.Reserve(GeoReferencingSystem ? 12 : 9);
312
313 Row.Add(MeshName);
314 Row.Add(FString::Printf(TEXT("%.0f"), Data.InstanceID));
315
316 // TODO add semantic label to the CSV
317 Row.Add(FString::Printf(TEXT("%.2f"), Location.X));
318 Row.Add(FString::Printf(TEXT("%.2f"), Location.Y));
319 Row.Add(FString::Printf(TEXT("%.2f"), Location.Z));
320 Row.Add(FString::Printf(TEXT("%.2f"), Rotation.Yaw));
321 Row.Add(FString::Printf(TEXT("%.2f"), Rotation.Pitch));
322 Row.Add(FString::Printf(TEXT("%.2f"), Rotation.Roll));
323
324 // Bounds
325 Row.Add(FString::Printf(TEXT("Origin=(%.2f,%.2f,%.2f),BoxExtent=(%.2f,%.2f,%.2f),SphereRadius=%.2f"),
326 Bounds.Origin.X, Bounds.Origin.Y, Bounds.Origin.Z,
327 Bounds.BoxExtent.X, Bounds.BoxExtent.Y, Bounds.BoxExtent.Z,
328 Bounds.SphereRadius));
329
331 {
332 const FGeographicCoordinates GeoCoords = UCoordinateConversionUtilities::UnrealToGeographicCoordinates(GeoReferencingSystem, Location);
333 Row.Add(FString::Printf(TEXT("%.8f"), GeoCoords.Latitude));
334 Row.Add(FString::Printf(TEXT("%.8f"), GeoCoords.Longitude));
335 Row.Add(FString::Printf(TEXT("%.8f"), GeoCoords.Altitude));
336 }
337
338 if (CSVFile)
339 {
340 CSVFile->WriteRow(Row);
341 }
342}
343
344void ATagger::TagLandscape(ALandscape* Landscape, AActor& Actor)
345{
346 if (!Landscape)
347 {
348 return;
349 }
350
351 constexpr float LANDSCAPE_ID = 0.0f;
352
353 // For some reason we needed to loop UStaticMeshComponents instead of ULandscapeComponents
354 TArray<UStaticMeshComponent*> StaticMeshComponents;
355 Actor.GetComponents<UStaticMeshComponent>(StaticMeshComponents);
356 for (UStaticMeshComponent* Component : StaticMeshComponents)
357 {
358 if (Component)
359 {
360 Component->SetRenderCustomDepth(true);
361 Component->SetCustomDepthStencilValue(static_cast<int32>(ELabels::Terrain) + 1);
362
363#ifdef InstanceSegmentationPass_EXISTS
364 // Set custom primitive data, used for instance segmentation.
365 Component->SetCustomPrimitiveDataVector4(4,
366 FVector4(LANDSCAPE_ID,
368 0.0f,
369 0.0f));
370#endif
371 }
372 }
373}
374
376{
377 const ELabels* FoundLabel = LabelMap.Find(String);
378 if (FoundLabel)
379 {
380 return *FoundLabel;
381 }
382 else
383 {
384#if WITH_EDITOR
385 UE_LOG(LogTemp, Warning, TEXT("Tagger.cpp: Missing Label: %s"), *String);
386#endif
387 return ELabels::None;
388 }
389}
390
391ELabels ATagger::GetLabelFromStaticComponent(UStaticMeshComponent* StaticMeshComponentPtr)
392{
393 ELabels Label = ELabels::None;
394
395 if (!StaticMeshComponentPtr)
396 {
397 return Label;
398 }
399
400 Label = GetLabelFromTag(StaticMeshComponentPtr);
401 if (Label != ELabels::None)
402 {
403 return Label;
404 }
405
406 UStaticMesh* MeshPtr = StaticMeshComponentPtr->GetStaticMesh();
407 if (MeshPtr)
408 {
409 FString Name;
410 Label = GetLabelFromPath(MeshPtr->GetPathName(), Name);
411
412 if (Label != ELabels::None)
413 {
414 StaticMeshComponentPtr->ComponentTags.Insert(FName(Name), 0);
415 }
416 }
417
418 return Label;
419}
420
421ELabels ATagger::GetLabelFromSkeletalMeshComponent(USkeletalMeshComponent* USkeletalMeshComponentPtr)
422{
423 ELabels Label = ELabels::None;
424
425 if (!USkeletalMeshComponentPtr)
426 {
427 return Label;
428 }
429
430 Label = GetLabelFromTag(USkeletalMeshComponentPtr);
431 if (Label != ELabels::None)
432 {
433 return Label;
434 }
435
436 USkeletalMesh* PhysicsAsset = USkeletalMeshComponentPtr->GetSkeletalMeshAsset();
437 if (PhysicsAsset)
438 {
439 FString Name;
440 Label = GetLabelFromPath(PhysicsAsset->GetPathName(), Name);
441
442 if (Label != ELabels::None)
443 {
444 USkeletalMeshComponentPtr->ComponentTags.Insert(FName(Name), 0);
445 }
446 }
447
448 return Label;
449}
450
451ELabels ATagger::GetLabelFromPath(const FString& Path, FString& FolderName)
452{
453 ELabels Label = ELabels::None;
454
455 // If the Path doesn't contain Models,
456 // the asset is not under /Content/Agrarsense/Models directory
457 // meaing we ignore it.
458 if (!Path.Contains("Models"))
459 {
460 return Label;
461 }
462
463 TArray<FString> StringArray;
464 Path.ParseIntoArray(StringArray, TEXT("/"), false);
465
466 FolderName = StringArray[StringArray.Num() - 2];
467
468 Label = GetLabelFromString(FolderName);
469
470 return Label;
471}
ELabels
Definition: ObjectLabel.h:14
static auto CastEnum(T label)
Definition: Tagger.cpp:96
void ExportObjectLocationsToCSV()
Definition: Tagger.cpp:198
virtual void BeginPlay() override
Definition: Tagger.cpp:31
void CreateCSVFile()
Definition: Tagger.cpp:238
TMap< FString, ELabels > LabelMap
Definition: Tagger.h:115
void WriteComponentToCSV(const FTaggedActorData Data)
Definition: Tagger.cpp:268
ELabels GetLabelFromPath(const FString &Path, FString &FolderName)
Definition: Tagger.cpp:451
ELabels GetLabelFromStaticComponent(UStaticMeshComponent *StaticMeshComponentPtr)
Definition: Tagger.cpp:391
void OnActorSpawned(AActor *Actor)
Definition: Tagger.cpp:87
ELabels GetLabelFromTag(const T *Object)
Definition: Tagger.h:95
void TagExistingActors()
Definition: Tagger.cpp:63
float ID
Definition: Tagger.h:123
AGeoReferencingSystem * GeoReferencingSystem
Definition: Tagger.h:107
TArray< FTaggedActorData > TaggedActors
Definition: Tagger.h:111
ATagger()
Definition: Tagger.cpp:26
void TagActor(AActor &Actor)
Definition: Tagger.cpp:101
UCSVFile * CSVFile
Definition: Tagger.h:109
FDelegateHandle ActorSpawnedDelegateHandle
Definition: Tagger.h:113
ELabels GetLabelFromSkeletalMeshComponent(USkeletalMeshComponent *USkeletalMeshComponentPtr)
Definition: Tagger.cpp:421
AActor * GetActorByInstanceID(float InstanceID)
Definition: Tagger.cpp:225
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override
Definition: Tagger.cpp:55
float SetStencilValue(UPrimitiveComponent &Component, AActor &Actor, const ELabels &Label)
Definition: Tagger.cpp:170
ELabels GetLabelFromString(const FString &String)
Definition: Tagger.cpp:375
void TagLandscape(ALandscape *Landscape, AActor &Actor)
Definition: Tagger.cpp:344
static bool IsPlayingInMainMenu()
static UCSVFile * CreateCSVFile(const FString &FileNameWithoutExtension, const FCSVFileSettings &Settings)
Definition: CSVFile.cpp:14
void Close()
Definition: CSVFile.cpp:115
void WriteRow(const TArray< FString > &Cells)
Definition: CSVFile.cpp:77
static FGeographicCoordinates UnrealToGeographicCoordinates(AGeoReferencingSystem *GeoReferencingSystem, const FVector &Position)
bool CreateUnique
Definition: CSVFile.h:42
ECSVDelimiter Delimiter
Definition: CSVFile.h:36
int32 QueueSize
Definition: CSVFile.h:48
FCSVFileWriteOptions FileWriteOption
Definition: CSVFile.h:45
float InstanceID
Definition: Tagger.h:37
ELabels Label
Definition: Tagger.h:40
AActor * Actor
Definition: Tagger.h:28
UStaticMeshComponent * StaticMeshComponent
Definition: Tagger.h:31
USkeletalMeshComponent * SkeletalMeshComponent
Definition: Tagger.h:34