17#include "NiagaraComponent.h"
18#include "Components/PrimitiveComponent.h"
19#include "Materials/Material.h"
20#include "ImageUtils.h"
21#include "Async/Async.h"
22#include "HighResScreenshot.h"
23#include "ImageWriteTask.h"
24#include "ImageWriteQueue.h"
25#include "Misc/DateTime.h"
26#include "Math/Color.h"
27#include "Blueprint/UserWidget.h"
28#include "GameFramework/PlayerController.h"
29#include "GeoReferencingSystem.h"
30#include "TimerManager.h"
31#include "GameFramework/SpringArmComponent.h"
33ACamera::ACamera(
const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
35 PrimaryActorTick.bCanEverTick =
true;
36 PrimaryActorTick.TickGroup = TG_PostUpdateWork;
38 CaptureRenderTarget = CreateDefaultSubobject<UTextureRenderTarget2D>(FName(*FString::Printf(TEXT(
"CaptureRenderTarget"))));
46 CaptureComponent2D = CreateDefaultSubobject<USceneCaptureComponent2D>(FName(*FString::Printf(TEXT(
"SceneCaptureComponent2D"))));
48 CaptureComponent2D->PrimitiveRenderMode = ESceneCapturePrimitiveRenderMode::PRM_RenderScenePrimitives;
61 UMaterial* PostProcessingMat = Cast<UMaterial>(StaticLoadObject(UMaterial::StaticClass(),
nullptr, *Path));
65 PostProcessSettings.AddBlendable(PostProcessingMat, Weight);
69 const FString ErrorMessage = FString::Printf(TEXT(
"Failed to add post-processing material to sensor: %s"), *
GetSensorName());
79 PostProcessSettings.RemoveBlendable(Material);
107 LogFile = NewObject<ULogFile>(ULogFile::StaticClass());
110 const FString FileName =
"camera_metadata";
117 WriteToLogFile(
"timestamp, image_name, X location, Y location, Z location, yaw rotation, pitch rotation, roll rotation, GPS latitude, GPS longitude, GPS altitude");
121 WriteToLogFile(
"timestamp, image_name, X location, Y location, Z location, yaw rotation, pitch rotation, roll rotation");
131 UE_LOG(LogTemp, Warning, TEXT(
"Camera.cpp: CaptureComponent2D is nullptr!"));
152 const FString Path =
"/Game/Agrarsense/Materials/PostProcessingMaterials/PhysicLensDistortion.PhysicLensDistortion";
153 PhysicLensDistortion = Cast<UMaterial>(StaticLoadObject(UMaterial::StaticClass(),
nullptr, *Path));
159 UE_LOG(LogTemp, Warning, TEXT(
"Camera.cpp: Added physics lens distortion effect."));
169 UE_LOG(LogTemp, Warning, TEXT(
"Camera.cpp: Removed physics lens distortion effect."));
177 const FString Path =
"/Game/Agrarsense/Materials/PostProcessingMaterials/CameraPostProcessEffects/m_ice_lens_effect";
178 UMaterial* LoadedIceMaterial = Cast<UMaterial>(StaticLoadObject(UMaterial::StaticClass(),
nullptr, *Path));
187 UE_LOG(LogTemp, Warning, TEXT(
"Camera.cpp: Added ice lens effect."));
197 IceMatInstance->SetScalarParameterValue(FName(
"Angle"), parameters.
IceLensEffectAngle);
199 UE_LOG(LogTemp, Warning, TEXT(
"Camera.cpp: Changed ice lens effect parameters."));
209 PostProcessSettings.RemoveBlendable(IceMatInstance);
213 UE_LOG(LogTemp, Warning, TEXT(
"Camera.cpp: Removed ice lens effect."));
228 PostProcessSettings.bOverride_AutoExposureMethod = UsePostProcessingEffects;
229 PostProcessSettings.bOverride_AutoExposureBias = UsePostProcessingEffects;
230 PostProcessSettings.bOverride_AutoExposureMinBrightness = UsePostProcessingEffects;
231 PostProcessSettings.bOverride_AutoExposureMaxBrightness = UsePostProcessingEffects;
232 PostProcessSettings.bOverride_AutoExposureSpeedUp = UsePostProcessingEffects;
233 PostProcessSettings.bOverride_AutoExposureSpeedDown = UsePostProcessingEffects;
234 PostProcessSettings.bOverride_HistogramLogMin = UsePostProcessingEffects;
235 PostProcessSettings.bOverride_HistogramLogMax = UsePostProcessingEffects;
236 PostProcessSettings.bOverride_CameraShutterSpeed = UsePostProcessingEffects;
237 PostProcessSettings.bOverride_CameraISO = UsePostProcessingEffects;
238 PostProcessSettings.bOverride_DepthOfFieldFstop = UsePostProcessingEffects;
239 PostProcessSettings.bOverride_DepthOfFieldMinFstop = UsePostProcessingEffects;
240 PostProcessSettings.bOverride_DepthOfFieldBladeCount = UsePostProcessingEffects;
241 PostProcessSettings.bOverride_FilmSlope = UsePostProcessingEffects;
242 PostProcessSettings.bOverride_FilmToe = UsePostProcessingEffects;
243 PostProcessSettings.bOverride_FilmShoulder = UsePostProcessingEffects;
244 PostProcessSettings.bOverride_FilmWhiteClip = UsePostProcessingEffects;
245 PostProcessSettings.bOverride_FilmBlackClip = UsePostProcessingEffects;
246 PostProcessSettings.bOverride_MotionBlurAmount = UsePostProcessingEffects;
247 PostProcessSettings.bOverride_MotionBlurMax = UsePostProcessingEffects;
248 PostProcessSettings.bOverride_MotionBlurPerObjectSize = UsePostProcessingEffects;
249 PostProcessSettings.bOverride_WhiteTemp = UsePostProcessingEffects;
250 PostProcessSettings.bOverride_WhiteTint = UsePostProcessingEffects;
251 PostProcessSettings.bOverride_ColorContrast = UsePostProcessingEffects;
252 PostProcessSettings.bOverride_SceneFringeIntensity = UsePostProcessingEffects;
253 PostProcessSettings.bOverride_ChromaticAberrationStartOffset = UsePostProcessingEffects;
254 PostProcessSettings.bOverride_AmbientOcclusionIntensity = UsePostProcessingEffects;
255 PostProcessSettings.bOverride_AmbientOcclusionRadius = UsePostProcessingEffects;
256 PostProcessSettings.bOverride_AmbientOcclusionStaticFraction = UsePostProcessingEffects;
257 PostProcessSettings.bOverride_AmbientOcclusionFadeDistance = UsePostProcessingEffects;
258 PostProcessSettings.bOverride_AmbientOcclusionPower = UsePostProcessingEffects;
259 PostProcessSettings.bOverride_AmbientOcclusionBias = UsePostProcessingEffects;
260 PostProcessSettings.bOverride_AmbientOcclusionQuality = UsePostProcessingEffects;
261 PostProcessSettings.bOverride_BloomMethod = UsePostProcessingEffects;
262 PostProcessSettings.bOverride_BloomIntensity = UsePostProcessingEffects;
263 PostProcessSettings.bOverride_BloomThreshold = UsePostProcessingEffects;
264 PostProcessSettings.bOverride_LensFlareIntensity = UsePostProcessingEffects;
265 PostProcessSettings.bOverride_DepthOfFieldFocalDistance = UsePostProcessingEffects;
266 PostProcessSettings.bOverride_DepthOfFieldDepthBlurAmount = UsePostProcessingEffects;
267 PostProcessSettings.bOverride_DepthOfFieldDepthBlurRadius = UsePostProcessingEffects;
325 const FString Encoding =
"bgr8";
329 ImageMsg = MakeShared<ROSMessages::sensor_msgs::Image>();
330 ImageMsg->header.frame_id =
"world";
350 FSoftClassPath WidgetClassPath(TEXT(
"/Game/Agrarsense/Widgets/Camera/WBP_CameraControlsMenu.WBP_CameraControlsMenu_C"));
351 UClass* WidgetClass = WidgetClassPath.TryLoadClass<UUserWidget>();
353 APlayerController* PlayerController = UGameplayStatics::GetPlayerController(GetWorld(), 0);
355 if (WidgetClass && PlayerController)
357 UCameraWidgetBase* WidgetInstance = CreateWidget<UCameraWidgetBase>(PlayerController, WidgetClass);
360 bool ShowGuide =
false;
361 WidgetInstance->
Setup(
this, ShowGuide);
367 bool Resized =
false;
403 SetActorTickEnabled(
false);
408 SetActorTickEnabled(
true);
414 for (int32 i = 0; i < Components.Num(); i++)
416 UPrimitiveComponent* Primitive = Components[i].Get();
425 GetWorld()->GetTimerManager().SetTimerForNextTick([
this]()
429 DronePtr = Cast<APIDDrone>(GetAttachParentActor());
440 Super::EndPlay(EndPlayReason);
499 SetActorRotation(gimbalRot);
567 TArray<FCapturedFrameData> Frames =
FrameGrabber->GetCapturedFrames();
570 FCapturedFrameData& LastFrame = Frames.Last();
571 TArray<FColor>& ImageBuffer = LastFrame.ColorBuffer;
583 AsyncTask(ENamedThreads::AnyBackgroundThreadNormalTask, [
this, ImageBuffer]()
600 static uint8 GammaLUT[256];
601 static bool LUTInitialized =
false;
604 LUTInitialized =
true;
605 for (int32 i = 0; i < 256; ++i)
607 float Linear = FMath::Pow(i / 255.0f, 2.2f);
608 GammaLUT[i] = FMath::RoundToInt(Linear * 255.0f);
612 FColor* RESTRICT BufferPtr = Buffer.GetData();
613 const int32 Num = Buffer.Num();
615 const int32 ChunkSize = 512;
616 const int32 NumChunks = (Num + ChunkSize - 1) / ChunkSize;
618 ParallelFor(NumChunks, [BufferPtr, Num](int32 ChunkIndex)
620 const int32 Start = ChunkIndex * ChunkSize;
621 const int32 End = FMath::Min(Start + ChunkSize, Num);
623 for (int32 i = Start; i < End; ++i)
625 FColor& C = BufferPtr[i];
646 UE_LOG(LogTemp, Warning, TEXT(
"Camera.cpp: UnrealWindow is nullptr!"));
654 TSharedPtr<FSceneViewport> SceneViewport =
UnrealWindow->GetSceneViewport();
657 EPixelFormat PixelFormat = GetPixelFormatFromRenderTargetFormat(
TextureFormat);
658 FIntPoint Size = SceneViewport->GetSize();
667 FrameGrabber = MakeShareable(
new FFrameGrabber(SceneViewport.ToSharedRef(), Size, PixelFormat));
697 || FrameBuffer.IsEmpty()
713 const int32 BufferSize = Width * Height * 3;
722 const FColor* RESTRICT Source = FrameBuffer.GetData();
724 const int32 PixelCount = FrameBuffer.Num();
725 const int32 ChunkSize = 512;
726 const int32 NumChunks = (PixelCount + ChunkSize - 1) / ChunkSize;
728 ParallelFor(NumChunks, [Source, Dest, ChunkSize, PixelCount](int32 ChunkIndex)
730 const int32 StartIndex = ChunkIndex * ChunkSize;
731 const int32 EndIndex = FMath::Min(StartIndex + ChunkSize, PixelCount);
733 for (int32 i = StartIndex; i < EndIndex; ++i)
735 const FColor& Pixel = Source[i];
736 const int32 j = i * 3;
737 Dest[j + 0] = Pixel.B;
738 Dest[j + 1] = Pixel.G;
739 Dest[j + 2] = Pixel.R;
748 ImageMsg->header.time = FROSTime::Now();
757 if (FrameBuffer.IsEmpty() || Width == 0 || Height == 0)
762 int32 Size = Width * Height;
763 if (FrameBuffer.Num() != Size)
765 const FString Msg =
"Camera sensor: Unable to save Image to disk. FrameBuffer size and resolution don't match!";
770 const FString ImageName = FString::Printf(TEXT(
"image_%d.png"),
ImageNumber);
771 const FString FullFileName = FString::Printf(TEXT(
"%s%s"), *
FileSavePath, *ImageName);
776 FIntPoint DestSize(Width, Height);
777 TImagePixelData<FColor> PixelData(DestSize);
778 PixelData.Pixels = FrameBuffer;
781 TUniquePtr<FImageWriteTask> ImageTask = MakeUnique<FImageWriteTask>();
782 ImageTask->PixelData = MakeUnique<TImagePixelData<FColor>>(PixelData);
783 ImageTask->Filename = FullFileName;
784 ImageTask->Format = EImageFormat::PNG;
785 ImageTask->CompressionQuality = (int32)EImageCompressionQuality::Default;
786 ImageTask->bOverwriteFile =
true;
787 ImageTask->PixelPreProcessors.Add(TAsyncAlphaWrite<FColor>(255));
790 FHighResScreenshotConfig& HighResScreenshotConfig = GetHighResScreenshotConfig();
791 TFuture<bool> CompletionFuture = HighResScreenshotConfig.ImageWriteQueue->Enqueue(MoveTemp(ImageTask));
802 const FVector ActorPosition = GetActorLocation();
803 const FRotator ActorRotation = GetActorRotation();
811 MetaData = FString::Printf(TEXT(
"%s, %s, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %.8f, %.8f, %.8f"),
812 *TimeStamp, *ImageName,
813 ActorPosition.X, ActorPosition.Y, ActorPosition.Z,
814 ActorRotation.Pitch, ActorRotation.Yaw, ActorRotation.Roll,
815 GeoCoordinates.Latitude, GeoCoordinates.Longitude, GeoCoordinates.Altitude);
819 MetaData = FString::Printf(TEXT(
"%s, %s, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f"),
820 *TimeStamp, *ImageName,
821 ActorPosition.X, ActorPosition.Y, ActorPosition.Z,
822 ActorRotation.Pitch, ActorRotation.Yaw, ActorRotation.Roll);
832 UE_LOG(LogTemp, Warning, TEXT(
"Camera.cpp: Camera window closed. Destroying Camera sensor.."));
863 CameraShowFlags.SetDynamicShadows(RenderShadows);
864 CameraShowFlags.SetContactShadows(RenderShadows);
865 CameraShowFlags.SetCapsuleShadows(RenderShadows);
874 CameraShowFlags.SetTemporalAA(SetTemporal);
880 if (Width == 0 || Height == 0)
907 ShowFlags.SetDeferredLighting(
false);
908 ShowFlags.SetSkyLighting(
false);
909 ShowFlags.SetAmbientOcclusion(
false);
910 ShowFlags.SetAntiAliasing(
false);
911 ShowFlags.SetVolumetricFog(
false);;
912 ShowFlags.SetBloom(
false);
913 ShowFlags.SetCameraImperfections(
false);
914 ShowFlags.SetCameraInterpolation(
false);
915 ShowFlags.SetColorGrading(
false);
916 ShowFlags.SetDepthOfField(
false);
917 ShowFlags.SetDiffuse(
false);
918 ShowFlags.SetDirectionalLights(
false);
919 ShowFlags.SetDirectLighting(
false);
920 ShowFlags.SetDynamicShadows(
false);
921 ShowFlags.SetEyeAdaptation(
false);
922 ShowFlags.SetFog(
false);
923 ShowFlags.SetGlobalIllumination(
false);
924 ShowFlags.SetGrain(
false);
925 ShowFlags.SetHLODColoration(
false);
926 ShowFlags.SetHMDDistortion(
false);
927 ShowFlags.SetLensFlares(
false);
928 ShowFlags.SetLightComplexity(
false);
929 ShowFlags.SetLightFunctions(
false);
930 ShowFlags.SetLightInfluences(
false);
931 ShowFlags.SetLighting(
false);
932 ShowFlags.SetLightMapDensity(
false);
933 ShowFlags.SetLightRadius(
false);
934 ShowFlags.SetLightShafts(
false);
935 ShowFlags.SetLODColoration(
false);
936 ShowFlags.SetMotionBlur(
false);
937 ShowFlags.SetOnScreenDebug(
false);
938 ShowFlags.SetParticles(
false);
939 ShowFlags.SetPointLights(
false);
940 ShowFlags.SetRefraction(
false);
941 ShowFlags.SetSceneColorFringe(
false);
942 ShowFlags.SetScreenSpaceAO(
false);
943 ShowFlags.SetScreenSpaceReflections(
false);
944 ShowFlags.SetSkyLighting(
false);
945 ShowFlags.SetSpotLights(
false);
946 ShowFlags.SetStationaryLightOverlap(
false);
947 ShowFlags.SetSubsurfaceScattering(
false);
948 ShowFlags.SetTonemapper(
false);
949 ShowFlags.SetVisualizeBuffer(
false);
950 ShowFlags.SetVisualizeDistanceFieldAO(
false);
951 ShowFlags.SetVisualizeDOF(
false);
952 ShowFlags.SetVisualizeHDR(
false);
953 ShowFlags.SetVisualizeLightCulling(
false);
954 ShowFlags.SetVisualizeMeshDistanceFields(
false);
955 ShowFlags.SetVisualizeMotionBlur(
false);
956 ShowFlags.SetVisualizeOutOfBoundsPixels(
false);
957 ShowFlags.SetVisualizeSenses(
false);
958 ShowFlags.SetVisualizeShadingModels(
false);
959 ShowFlags.SetVisualizeSSR(
false);
960 ShowFlags.SetVisualizeSSS(
false);
static auto BindTick(ObjectType *Object, FunctionType Function)
void AddPostProcessingMaterial(const FString &Path, float Weight=1.0f)
TSharedPtr< FFrameGrabber > FrameGrabber
void ChangeCameraParameters(FCameraBaseParameters newParameters)
virtual ESensorTypes GetSensorType() const override
FCameraBaseParameters CameraParameters
void ApplyGammaCorrectionLUT(TArray< FColor > &Buffer)
FOnWindowClosed OnWindowClosedDelegate
void AddHiddenActor(AActor *Actor)
virtual void Init(FCameraBaseParameters parameters, bool SimulateSensor=true)
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override
USceneCaptureComponent2D * CaptureComponent2D
void RemovePostProcessingMaterial(UMaterial *Material)
void SaveCameraMetaDataToDisk(const FString &ImageName)
AGeoReferencingSystem * GeoReferencingSystem
void SaveImageToDisk(const TArray< FColor > FrameBuffer, int32 Width, int32 Height)
FDelegateHandle OnPostTickDelegate
bool ShouldSimulateCamera
void SetShadowRendering(bool RenderShadows)
void OnWindowClosed(const TSharedRef< SWindow > &Window)
void FrameGrabberCapture()
void SendImageDataToROS(const TArray< FColor > &FrameBuffer, int32 Width, int32 Height)
FDelegateHandle OnPreTickDelegate
UTextureRenderTarget2D * CaptureRenderTarget
void AddWidgetToWindow(UWidget *WidgetToAdd)
TSharedPtr< ROSMessages::sensor_msgs::Image > ImageMsg
FRotator SensorSetRotation
bool SaveCurrentFrameToDiskRequested
void SetTemporalAA(bool SetTemporal)
void CreateLogFile() override
UTexture2D * CaptureFrameTexture
void SetupCamera(FCameraBaseParameters parameters)
TWeakObjectPtr< UMaterial > PhysicLensDistortion
void RemoveWidgetFromWindow(UWidget *WidgetToRemove)
FCameraDelegate_OnWindowResized OnCameraWindowResized
void HidePrimitiveComponent(UPrimitiveComponent *PrimitiveComponent)
TEnumAsByte< ETextureRenderTargetFormat > TextureFormat
void ReleaseFrameGrabber()
void EndOfFrameParellel(float DeltaTime)
virtual void AddProcessingToFrameBuffer(TArray< FColor > &buffer)
void ResizeCamera(int32 Width=1280, int32 Height=720)
TSharedPtr< FUnrealWindow > UnrealWindow
void EndOfFrame(UWorld *World, ELevelTick TickType, float DeltaSeconds)
ACamera(const FObjectInitializer &ObjectInitializer)
void PreActorTick(UWorld *World, ELevelTick TickType, float DeltaSeconds)
FCameraDelegate_OnWindowClosed OnCameraWindowClosed
virtual void BeginPlay() override
TWeakObjectPtr< UMaterialInstanceDynamic > IceMaterialInstance
bool ShouldSimulate(const float DeltaSeconds)
bool CanSimulateSensor() const
static FPrimitiveAdded OnPrimitiveAdded
FString GetSensorIdentifier() const
virtual void CreateDataSavePath()
FString GetSensorName() const
void SetSimulateSensor(bool SimulateSensor)
UTopic * GetROSTopic() const
static TArray< TWeakObjectPtr< UPrimitiveComponent > > GetComponentsToHide()
FString CreateTimeStampString() const
void WriteToLogFile(const FString &Message)
FORCEINLINE bool IsROSConnected() const
virtual void CreateROSTopic()
static void RemoveTick(FTickEntry TickEntry)
static FTickEntry AddTick(UObject *Object, std::function< void(float)> Function, ETickType Type)
bool IsVehicleInGarage() const
static void Log(const FString &Message, bool LogToTextFile=true, bool LogToROS=true)
static bool ShouldStartWindowMinimized()
static FGeographicCoordinates UnrealToGeographicCoordinates(AGeoReferencingSystem *GeoReferencingSystem, const FVector &Position)
void Create(const FString &FileNameWithoutExtension, FLogFileSettings Settings)
bool UsePhysicLensDistortionEffect
float MaxViewDistanceInCmOverride
float ExposureMaxBrightness
float IceLensEffectStrength
float MotionBlurMinObjSize
float ExposureMinBrightness
float MotionBlurIntensity
bool PostProcessingEffects
float ChromAberrIntensity
FFileWriteOptions FileWriteOptions
FFileCreationOptions FileCreationOptions