-
Notifications
You must be signed in to change notification settings - Fork 37
/
EgoVehicle.cpp
850 lines (737 loc) 路 33.7 KB
/
EgoVehicle.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
#include "EgoVehicle.h"
#include "Carla/Actor/ActorAttribute.h" // FActorAttribute
#include "Carla/Actor/ActorRegistry.h" // Register
#include "Carla/Game/CarlaStatics.h" // GetCurrentEpisode
#include "Carla/Vehicle/CarlaWheeledVehicleState.h" // ECarlaWheeledVehicleState
#include "DReyeVRPawn.h" // ADReyeVRPawn
#include "DrawDebugHelpers.h" // Debug Line/Sphere
#include "Engine/EngineTypes.h" // EBlendMode
#include "Engine/World.h" // GetWorld
#include "GameFramework/Actor.h" // Destroy
#include "Kismet/KismetSystemLibrary.h" // PrintString, QuitGame
#include "Math/Rotator.h" // RotateVector, Clamp
#include "Math/UnrealMathUtility.h" // Clamp
#include <algorithm>
// Sets default values
AEgoVehicle::AEgoVehicle(const FObjectInitializer &ObjectInitializer) : Super(ObjectInitializer)
{
LOG("Constructing Ego Vehicle: %s", *FString(this->GetName()));
ReadConfigVariables();
// this actor ticks AFTER the physics simulation is done
PrimaryActorTick.bCanEverTick = true;
PrimaryActorTick.TickGroup = TG_PostPhysics;
// Set up the root position to be the this mesh
SetRootComponent(GetMesh());
// Initialize the rigid body static mesh
ConstructRigidBody();
// Initialize the camera components
ConstructCameraRoot();
// Initialize audio components
ConstructEgoSounds();
// Initialize mirrors
ConstructMirrors();
// Initialize text render components
ConstructDashText();
// Initialize the steering wheel
ConstructSteeringWheel();
LOG("Finished constructing %s", *FString(this->GetName()));
}
void AEgoVehicle::ReadConfigVariables()
{
ReadConfigValue("EgoVehicle", "DashLocation", DashboardLocnInVehicle);
ReadConfigValue("EgoVehicle", "SpeedometerInMPH", bUseMPH);
ReadConfigValue("EgoVehicle", "EnableTurnSignalAction", bEnableTurnSignalAction);
ReadConfigValue("EgoVehicle", "TurnSignalDuration", TurnSignalDuration);
// mirrors
auto InitMirrorParams = [](const FString &Name, struct MirrorParams &Params) {
Params.Name = Name;
ReadConfigValue("Mirrors", Params.Name + "MirrorEnabled", Params.Enabled);
ReadConfigValue("Mirrors", Params.Name + "MirrorTransform", Params.MirrorTransform);
ReadConfigValue("Mirrors", Params.Name + "ReflectionTransform", Params.ReflectionTransform);
ReadConfigValue("Mirrors", Params.Name + "ScreenPercentage", Params.ScreenPercentage);
};
InitMirrorParams("Rear", RearMirrorParams);
InitMirrorParams("Left", LeftMirrorParams);
InitMirrorParams("Right", RightMirrorParams);
// rear mirror chassis
ReadConfigValue("Mirrors", "RearMirrorChassisTransform", RearMirrorChassisTransform);
// steering wheel
ReadConfigValue("SteeringWheel", "InitLocation", InitWheelLocation);
ReadConfigValue("SteeringWheel", "InitRotation", InitWheelRotation);
ReadConfigValue("SteeringWheel", "MaxSteerAngleDeg", MaxSteerAngleDeg);
ReadConfigValue("SteeringWheel", "SteeringScale", SteeringAnimScale);
// other/cosmetic
ReadConfigValue("EgoVehicle", "DrawDebugEditor", bDrawDebugEditor);
// inputs
ReadConfigValue("VehicleInputs", "ScaleSteeringDamping", ScaleSteeringInput);
ReadConfigValue("VehicleInputs", "ScaleThrottleInput", ScaleThrottleInput);
ReadConfigValue("VehicleInputs", "ScaleBrakeInput", ScaleBrakeInput);
// replay
ReadConfigValue("Replayer", "CameraFollowHMD", bCameraFollowHMD);
}
void AEgoVehicle::BeginPlay()
{
// Called when the game starts or when spawned
Super::BeginPlay();
// Get information about the world
World = GetWorld();
ensure(World != nullptr);
// initialize
InitAIPlayer();
// Bug-workaround for initial delay on throttle; see https://github.com/carla-simulator/carla/issues/1640
this->GetVehicleMovementComponent()->SetTargetGear(1, true);
// get the GameMode script
SetGame(Cast<ADReyeVRGameMode>(UGameplayStatics::GetGameMode(World)));
LOG("Initialized DReyeVR EgoVehicle");
}
void AEgoVehicle::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
// https://docs.unrealengine.com/4.27/en-US/API/Runtime/Engine/Engine/EEndPlayReason__Type/
if (EndPlayReason == EEndPlayReason::Destroyed)
{
LOG("DReyeVR EgoVehicle is being destroyed! You'll need to spawn another one!");
}
if (GetGame())
{
GetGame()->SetEgoVehicle(nullptr);
GetGame()->PossessSpectator();
}
if (this->Pawn)
{
this->Pawn->SetEgoVehicle(nullptr);
}
}
void AEgoVehicle::BeginDestroy()
{
Super::BeginDestroy();
// destroy all spawned entities
if (EgoSensor)
EgoSensor->Destroy();
LOG("EgoVehicle has been destroyed");
}
// Called every frame
void AEgoVehicle::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);
// Get the current data from the AEgoSensor and use it
UpdateSensor(DeltaSeconds);
// Update the positions based off replay data
ReplayTick();
// Draw debug lines on editor
DebugLines();
// Render EgoVehicle dashboard
UpdateDash();
// Update the steering wheel to be responsive to user input
TickSteeringWheel(DeltaSeconds);
// Ensure appropriate autopilot functionality is accessible from EgoVehicle
TickAutopilot();
// Update the world level
TickGame(DeltaSeconds);
// Play sound that requires constant ticking
TickSounds();
}
void AEgoVehicle::ConstructRigidBody()
{
#if 0
/// TODO: re-enable this code once spawning from DReyeVR needs to be done without a hardcoded blueprint asset
/// to see this effect remove the reference to EgoVehicleBPClass in DReyeVRFactory.cpp once implemented
// https://forums.unrealengine.com/t/cannot-create-vehicle-updatedcomponent-has-not-initialized-its-rigid-body-actor/461662
/// NOTE: this must be run in the constructors!
// load skeletal mesh (static mesh)
static ConstructorHelpers::FObjectFinder<USkeletalMesh> CarMesh(TEXT(
"SkeletalMesh'/Game/DReyeVR/EgoVehicle/model3/Mesh/SkeletalMesh_model3.SkeletalMesh_model3'"));
// original: "SkeletalMesh'/Game/Carla/Static/Car/4Wheeled/Tesla/SM_TeslaM3_v2.SM_TeslaM3_v2'"
USkeletalMesh *SkeletalMesh = CarMesh.Object;
if (SkeletalMesh == nullptr)
{
LOG_ERROR("Unable to load skeletal mesh!");
return;
}
// load skeleton (for animations)
static ConstructorHelpers::FObjectFinder<USkeleton> CarSkeleton(
TEXT("Skeleton'/Game/DReyeVR/EgoVehicle/model3/Mesh/Skeleton_model3.Skeleton_model3'"));
// original:
// "Skeleton'/Game/Carla/Static/Car/4Wheeled/Tesla/SM_TeslaM3_lights_body_Skeleton.SM_TeslaM3_lights_body_Skeleton'"
USkeleton *Skeleton = CarSkeleton.Object;
if (Skeleton == nullptr)
{
LOG_ERROR("Unable to load skeleton!");
return;
}
// load animations bp
static ConstructorHelpers::FClassFinder<UObject> AnimBPClass(
TEXT("/Game/DReyeVR/EgoVehicle/model3/Mesh/Animation_model3.Animation_model3_C"));
// original: "/Game/Carla/Static/Car/4Wheeled/Tesla/Tesla_Animation.Tesla_Animation_C"
auto AnimInstance = AnimBPClass.Class;
if (!AnimBPClass.Succeeded())
{
LOG_ERROR("Unable to load Animation!");
return;
}
// load physics asset
static ConstructorHelpers::FObjectFinder<UPhysicsAsset> CarPhysics(TEXT(
"PhysicsAsset'/Game/DReyeVR/EgoVehicle/model3/Mesh/Physics_model3.Physics_model3'"));
// original: "PhysicsAsset'/Game/Carla/Static/Car/4Wheeled/Tesla/SM_TeslaM3_PhysicsAsset.SM_TeslaM3_PhysicsAsset'"
UPhysicsAsset *PhysicsAsset = CarPhysics.Object;
if (PhysicsAsset == nullptr)
{
LOG_ERROR("Unable to load PhysicsAsset!");
return;
}
// contrary to https://docs.unrealengine.com/4.27/en-US/API/Runtime/Engine/Engine/USkeletalMesh/SetSkeleton/
SkeletalMesh->Skeleton = Skeleton;
SkeletalMesh->PhysicsAsset = PhysicsAsset;
SkeletalMesh->Build();
USkeletalMeshComponent *Mesh = GetMesh();
check(Mesh != nullptr);
Mesh->SetSkeletalMesh(SkeletalMesh, true);
Mesh->SetAnimInstanceClass(AnimInstance);
Mesh->SetPhysicsAsset(PhysicsAsset);
Mesh->RecreatePhysicsState();
this->GetVehicleMovementComponent()->RecreatePhysicsState();
// sanity checks
ensure(Mesh->GetPhysicsAsset() != nullptr);
LOG("Successfully created EgoVehicle rigid body");
#endif
}
/// ========================================== ///
/// ----------------:CAMERA:------------------ ///
/// ========================================== ///
void AEgoVehicle::ConstructCameraRoot()
{
// Spawn the RootComponent and Camera for the VR camera
VRCameraRoot = CreateDefaultSubobject<USceneComponent>(TEXT("VRCameraRoot"));
VRCameraRoot->SetupAttachment(GetRootComponent()); // The vehicle blueprint itself
VRCameraRoot->SetRelativeLocation(FVector::ZeroVector);
VRCameraRoot->SetRelativeRotation(FRotator::ZeroRotator);
// taking this names directly from the [CameraPose] params in DReyeVRConfig.ini
std::vector<FString> CameraPoses = {
"DriversSeat", // 1st
"ThirdPerson", // 2nd
"BirdsEyeView", // 3rd
"Front", // 4th
};
for (FString &Key : CameraPoses)
{
FVector Location;
FRotator Rotation;
ReadConfigValue("CameraPose", Key + "Loc", Location);
ReadConfigValue("CameraPose", Key + "Rot", Rotation);
// converting FString to std::string for hashing
FTransform Transform = FTransform(Rotation, Location, FVector::OneVector);
CameraTransforms.push_back(std::make_pair(Key, Transform));
}
// assign the starting camera root pose to the given starting pose
FString StartingPose;
ReadConfigValue("CameraPose", "StartingPose", StartingPose);
SetCameraRootPose(StartingPose);
}
void AEgoVehicle::SetCameraRootPose(const FString &CameraPoseName)
{
// given a string (key), index into the map to obtain the FTransform
FTransform CameraPoseTransform;
bool bFoundMatchingPair = false;
for (std::pair<FString, FTransform> &CamPose : CameraTransforms)
{
if (CamPose.first == CameraPoseName)
{
CameraPoseTransform = CamPose.second;
bFoundMatchingPair = true;
break;
}
}
ensure(bFoundMatchingPair == true); // yells at you if CameraPoseName was not found
SetCameraRootPose(CameraPoseTransform);
}
size_t AEgoVehicle::GetNumCameraPoses() const
{
return CameraTransforms.size();
}
void AEgoVehicle::SetCameraRootPose(size_t CameraPoseIdx)
{
// allow setting the camera root by indexing into CameraTransforms array
CameraPoseIdx = std::min(CameraPoseIdx, CameraTransforms.size() - 1);
SetCameraRootPose(CameraTransforms[CameraPoseIdx].second);
}
void AEgoVehicle::SetCameraRootPose(const FTransform &CameraPoseTransform)
{
// sets the base posision of the Camera root (where the camera is at "rest")
this->CameraPose = CameraPoseTransform;
// LOG("Setting camera pose to: %s", *(CameraPose + CameraPoseOffset).ToString());
// First, set the root of the camera to the driver's seat head pos
VRCameraRoot->SetRelativeLocation(CameraPose.GetLocation() + CameraPoseOffset.GetLocation());
VRCameraRoot->SetRelativeRotation(CameraPose.Rotator() + CameraPoseOffset.Rotator());
}
void AEgoVehicle::SetPawn(ADReyeVRPawn *PawnIn)
{
ensure(VRCameraRoot != nullptr);
this->Pawn = PawnIn;
ensure(Pawn != nullptr);
this->FirstPersonCam = Pawn->GetCamera();
ensure(FirstPersonCam != nullptr);
FAttachmentTransformRules F(EAttachmentRule::KeepRelative, false);
Pawn->AttachToComponent(VRCameraRoot, F);
FirstPersonCam->AttachToComponent(VRCameraRoot, F);
// Then set the actual camera to be at its origin (attached to VRCameraRoot)
FirstPersonCam->SetRelativeLocation(FVector::ZeroVector);
FirstPersonCam->SetRelativeRotation(FRotator::ZeroRotator);
}
const UCameraComponent *AEgoVehicle::GetCamera() const
{
ensure(FirstPersonCam != nullptr);
return FirstPersonCam;
}
UCameraComponent *AEgoVehicle::GetCamera()
{
ensure(FirstPersonCam != nullptr);
return FirstPersonCam;
}
FVector AEgoVehicle::GetCameraOffset() const
{
return VRCameraRoot->GetComponentLocation();
}
FVector AEgoVehicle::GetCameraPosn() const
{
return GetCamera() ? GetCamera()->GetComponentLocation() : FVector::ZeroVector;
}
FVector AEgoVehicle::GetNextCameraPosn(const float DeltaSeconds) const
{
// usually only need this is tick before physics
return GetCameraPosn() + DeltaSeconds * GetVelocity();
}
FRotator AEgoVehicle::GetCameraRot() const
{
return GetCamera() ? GetCamera()->GetComponentRotation() : FRotator::ZeroRotator;
}
const class AEgoSensor *AEgoVehicle::GetSensor() const
{
return const_cast<const class AEgoSensor *>(EgoSensor);
}
/// ========================================== ///
/// ---------------:AIPLAYER:----------------- ///
/// ========================================== ///
void AEgoVehicle::InitAIPlayer()
{
this->SpawnDefaultController(); // spawns default (AI) controller and gets possessed by it
auto PlayerController = this->GetController();
ensure(PlayerController != nullptr);
AI_Player = Cast<AWheeledVehicleAIController>(PlayerController);
ensure(AI_Player != nullptr);
}
void AEgoVehicle::SetAutopilot(const bool AutopilotOn)
{
bAutopilotEnabled = AutopilotOn;
AI_Player->SetAutopilot(bAutopilotEnabled);
AI_Player->SetStickyControl(bAutopilotEnabled);
}
bool AEgoVehicle::GetAutopilotStatus() const
{
return bAutopilotEnabled;
}
void AEgoVehicle::TickAutopilot()
{
ensure(AI_Player != nullptr);
if (AI_Player != nullptr)
{
bAutopilotEnabled = AI_Player->IsAutopilotEnabled();
}
}
/// ========================================== ///
/// ----------------:SENSOR:------------------ ///
/// ========================================== ///
void AEgoVehicle::InitSensor()
{
// update the world on refresh (ex. --reloadWorld)
World = GetWorld();
check(World != nullptr);
// Spawn the EyeTracker Carla sensor and attach to Ego-Vehicle:
{
UCarlaEpisode *Episode = UCarlaStatics::GetCurrentEpisode(World);
check(Episode != nullptr);
FActorDefinition EgoSensorDef = FindDefnInRegistry(Episode, AEgoSensor::StaticClass());
FActorDescription Description;
{ // create a Description from the Definition to spawn the actor
Description.UId = EgoSensorDef.UId;
Description.Id = EgoSensorDef.Id;
Description.Class = EgoSensorDef.Class;
}
if (Episode == nullptr)
{
LOG_ERROR("Null Episode in world!");
}
// calls Episode::SpawnActor => SpawnActorWithInfo => ActorDispatcher->SpawnActor => SpawnFunctions[UId]
FTransform SpawnPt = FTransform(FRotator::ZeroRotator, GetCameraPosn(), FVector::OneVector);
EgoSensor = static_cast<AEgoSensor *>(Episode->SpawnActor(SpawnPt, Description));
}
check(EgoSensor != nullptr);
// Attach the EgoSensor as a child to the EgoVehicle
EgoSensor->SetOwner(this);
EgoSensor->AttachToActor(this, FAttachmentTransformRules::KeepRelativeTransform);
EgoSensor->SetEgoVehicle(this);
if (DReyeVRGame)
EgoSensor->SetGame(DReyeVRGame);
}
void AEgoVehicle::ReplayTick()
{
const bool bIsReplaying = EgoSensor->IsReplaying();
// need to enable/disable VehicleMesh simulation
class USkeletalMeshComponent *VehicleMesh = GetMesh();
if (VehicleMesh)
VehicleMesh->SetSimulatePhysics(!bIsReplaying); // disable physics when replaying (teleporting)
if (FirstPersonCam)
FirstPersonCam->bLockToHmd = !bIsReplaying; // only lock orientation and position to HMD when not replaying
// perform all sensor updates that occur when replaying
if (bIsReplaying)
{
// this gets reached when the simulator is replaying data from a carla log
const DReyeVR::AggregateData *Replay = EgoSensor->GetData();
// include positional update here, else there is lag/jitter between the camera and the vehicle
// since the Carla Replayer tick differs from the EgoVehicle tick
const FTransform ReplayTransform(Replay->GetVehicleRotation(), // FRotator (Rotation)
Replay->GetVehicleLocation(), // FVector (Location)
FVector::OneVector); // FVector (Scale3D)
// see https://docs.unrealengine.com/4.26/en-US/API/Runtime/Engine/Engine/ETeleportType/
SetActorTransform(ReplayTransform, false, nullptr, ETeleportType::TeleportPhysics);
// set the camera reenactment orientation
{
const FTransform CameraOrientation =
bCameraFollowHMD // follow HMD reenacts all the head movmeents that were recorded
? FTransform(Replay->GetCameraRotation(), Replay->GetCameraLocation(), FVector::OneVector)
: FTransform::Identity; // otherwise just point forward (neutral position)
FirstPersonCam->SetRelativeTransform(CameraOrientation, false, nullptr, ETeleportType::TeleportPhysics);
}
// overwrite vehicle inputs to use the replay data
VehicleInputs = Replay->GetUserInputs();
}
}
void AEgoVehicle::UpdateSensor(const float DeltaSeconds)
{
if (EgoSensor == nullptr) // Spawn and attach the EgoSensor
{
// unfortunately World->SpawnActor *sometimes* fails if used in BeginPlay so
// calling it once in the tick is fine to avoid this crash.
InitSensor();
}
ensure(EgoSensor != nullptr);
if (EgoSensor == nullptr)
{
LOG_WARN("EgoSensor initialization failed!");
return;
}
// Explicitly update the EgoSensor here, synchronized with EgoVehicle tick
EgoSensor->ManualTick(DeltaSeconds); // Ensures we always get the latest data
}
/// ========================================== ///
/// ----------------:MIRROR:------------------ ///
/// ========================================== ///
void AEgoVehicle::MirrorParams::Initialize(class UStaticMeshComponent *MirrorSM,
class UPlanarReflectionComponent *Reflection,
class USkeletalMeshComponent *VehicleMesh)
{
check(MirrorSM != nullptr);
MirrorSM->SetupAttachment(VehicleMesh);
MirrorSM->SetRelativeLocation(MirrorTransform.GetLocation());
MirrorSM->SetRelativeRotation(MirrorTransform.Rotator());
MirrorSM->SetRelativeScale3D(MirrorTransform.GetScale3D());
MirrorSM->SetGenerateOverlapEvents(false); // don't collide with itself
MirrorSM->SetCollisionEnabled(ECollisionEnabled::NoCollision);
MirrorSM->SetVisibility(Enabled);
check(Reflection != nullptr);
Reflection->SetupAttachment(MirrorSM);
Reflection->SetRelativeLocation(ReflectionTransform.GetLocation());
Reflection->SetRelativeRotation(ReflectionTransform.Rotator());
Reflection->SetRelativeScale3D(ReflectionTransform.GetScale3D());
Reflection->NormalDistortionStrength = 0.0f;
Reflection->PrefilterRoughness = 0.0f;
Reflection->DistanceFromPlaneFadeoutStart = 1500.f;
Reflection->DistanceFromPlaneFadeoutEnd = 0.f;
Reflection->AngleFromPlaneFadeStart = 0.f;
Reflection->AngleFromPlaneFadeEnd = 90.f;
Reflection->PrefilterRoughnessDistance = 10000.f;
Reflection->ScreenPercentage = ScreenPercentage; // change this to reduce quality & improve performance
Reflection->bShowPreviewPlane = false;
Reflection->HideComponent(VehicleMesh);
Reflection->SetVisibility(Enabled);
/// TODO: use USceneCaptureComponent::ShowFlags to define what gets rendered in the mirror
// https://docs.unrealengine.com/4.27/en-US/API/Runtime/Engine/FEngineShowFlags/
}
void AEgoVehicle::ConstructMirrors()
{
class USkeletalMeshComponent *VehicleMesh = GetMesh();
/// Rear mirror
{
static ConstructorHelpers::FObjectFinder<UStaticMesh> RearSM(
TEXT("StaticMesh'/Game/DReyeVR/EgoVehicle/model3/Mirrors/RearMirror_model3.RearMirror_model3'"));
RearMirrorSM = CreateDefaultSubobject<UStaticMeshComponent>(FName(*(RearMirrorParams.Name + "MirrorSM")));
RearMirrorSM->SetStaticMesh(RearSM.Object);
RearReflection = CreateDefaultSubobject<UPlanarReflectionComponent>(FName(*(RearMirrorParams.Name + "Refl")));
RearMirrorParams.Initialize(RearMirrorSM, RearReflection, VehicleMesh);
// also add the chassis for this mirror
static ConstructorHelpers::FObjectFinder<UStaticMesh> RearChassisSM(
TEXT("StaticMesh'/Game/DReyeVR/EgoVehicle/model3/Mirrors/RearMirror_Mesh_model3.RearMirror_Mesh_model3'"));
RearMirrorChassisSM =
CreateDefaultSubobject<UStaticMeshComponent>(FName(*(RearMirrorParams.Name + "MirrorChassisSM")));
RearMirrorChassisSM->SetStaticMesh(RearChassisSM.Object);
RearMirrorChassisSM->SetupAttachment(VehicleMesh);
RearMirrorChassisSM->SetRelativeLocation(RearMirrorChassisTransform.GetLocation());
RearMirrorChassisSM->SetRelativeRotation(RearMirrorChassisTransform.Rotator());
RearMirrorChassisSM->SetRelativeScale3D(RearMirrorChassisTransform.GetScale3D());
RearMirrorChassisSM->SetGenerateOverlapEvents(false); // don't collide with itself
RearMirrorChassisSM->SetCollisionEnabled(ECollisionEnabled::NoCollision);
RearMirrorChassisSM->SetVisibility(RearMirrorParams.Enabled);
RearMirrorSM->SetupAttachment(RearMirrorChassisSM);
RearReflection->HideComponent(RearMirrorChassisSM); // don't show this in the reflection
}
/// Left mirror
{
static ConstructorHelpers::FObjectFinder<UStaticMesh> LeftSM(
TEXT("StaticMesh'/Game/DReyeVR/EgoVehicle/model3/Mirrors/LeftMirror_model3.LeftMirror_model3'"));
LeftMirrorSM = CreateDefaultSubobject<UStaticMeshComponent>(FName(*(LeftMirrorParams.Name + "MirrorSM")));
LeftMirrorSM->SetStaticMesh(LeftSM.Object);
LeftReflection = CreateDefaultSubobject<UPlanarReflectionComponent>(FName(*(LeftMirrorParams.Name + "Refl")));
LeftMirrorParams.Initialize(LeftMirrorSM, LeftReflection, VehicleMesh);
}
/// Right mirror
{
static ConstructorHelpers::FObjectFinder<UStaticMesh> RightSM(
TEXT("StaticMesh'/Game/DReyeVR/EgoVehicle/model3/Mirrors/RightMirror_model3.RightMirror_model3'"));
RightMirrorSM = CreateDefaultSubobject<UStaticMeshComponent>(FName(*(RightMirrorParams.Name + "MirrorSM")));
RightMirrorSM->SetStaticMesh(RightSM.Object);
RightReflection = CreateDefaultSubobject<UPlanarReflectionComponent>(FName(*(RightMirrorParams.Name + "Refl")));
RightMirrorParams.Initialize(RightMirrorSM, RightReflection, VehicleMesh);
}
}
/// ========================================== ///
/// ----------------:SOUNDS:------------------ ///
/// ========================================== ///
void AEgoVehicle::ConstructEgoSounds()
{
// Initialize ego-centric audio components
// See ACarlaWheeledVehicle::ConstructSounds for all Vehicle sounds
ensureMsgf(EngineRevSound != nullptr, TEXT("Vehicle engine rev should be initialized!"));
ensureMsgf(CrashSound != nullptr, TEXT("Vehicle crash sound should be initialized!"));
static ConstructorHelpers::FObjectFinder<USoundWave> GearSound(
TEXT("SoundWave'/Game/DReyeVR/Sounds/GearShift.GearShift'"));
GearShiftSound = CreateDefaultSubobject<UAudioComponent>(TEXT("GearShift"));
GearShiftSound->SetupAttachment(GetRootComponent());
GearShiftSound->bAutoActivate = false;
GearShiftSound->SetSound(GearSound.Object);
static ConstructorHelpers::FObjectFinder<USoundWave> TurnSignalSoundWave(
TEXT("SoundWave'/Game/DReyeVR/Sounds/TurnSignal.TurnSignal'"));
TurnSignalSound = CreateDefaultSubobject<UAudioComponent>(TEXT("TurnSignal"));
TurnSignalSound->SetupAttachment(GetRootComponent());
TurnSignalSound->bAutoActivate = false;
TurnSignalSound->SetSound(TurnSignalSoundWave.Object);
}
void AEgoVehicle::PlayGearShiftSound(const float DelayBeforePlay) const
{
if (this->GearShiftSound)
GearShiftSound->Play(DelayBeforePlay);
}
void AEgoVehicle::PlayTurnSignalSound(const float DelayBeforePlay) const
{
if (this->TurnSignalSound)
this->TurnSignalSound->Play(DelayBeforePlay);
}
void AEgoVehicle::SetVolume(const float VolumeIn)
{
if (GearShiftSound)
GearShiftSound->SetVolumeMultiplier(VolumeIn);
if (TurnSignalSound)
TurnSignalSound->SetVolumeMultiplier(VolumeIn);
Super::SetVolume(VolumeIn);
}
/// ========================================== ///
/// -----------------:DASH:------------------- ///
/// ========================================== ///
void AEgoVehicle::ConstructDashText() // dashboard text (speedometer, turn signals, gear shifter)
{
// Create speedometer
Speedometer = CreateDefaultSubobject<UTextRenderComponent>(TEXT("Speedometer"));
Speedometer->AttachToComponent(GetRootComponent(), FAttachmentTransformRules::KeepRelativeTransform);
Speedometer->SetRelativeLocation(DashboardLocnInVehicle);
Speedometer->SetRelativeRotation(FRotator(0.f, 180.f, 0.f)); // need to flip it to get the text in driver POV
Speedometer->SetTextRenderColor(FColor::Red);
Speedometer->SetText(FText::FromString("0"));
Speedometer->SetXScale(1.f);
Speedometer->SetYScale(1.f);
Speedometer->SetWorldSize(10); // scale the font with this
Speedometer->SetVerticalAlignment(EVerticalTextAligment::EVRTA_TextCenter);
Speedometer->SetHorizontalAlignment(EHorizTextAligment::EHTA_Center);
SpeedometerScale = CmPerSecondToXPerHour(bUseMPH);
// Create turn signals
TurnSignals = CreateDefaultSubobject<UTextRenderComponent>(TEXT("TurnSignals"));
TurnSignals->AttachToComponent(GetRootComponent(), FAttachmentTransformRules::KeepRelativeTransform);
TurnSignals->SetRelativeLocation(DashboardLocnInVehicle + FVector(0, 11.f, -5.f));
TurnSignals->SetRelativeRotation(FRotator(0.f, 180.f, 0.f)); // need to flip it to get the text in driver POV
TurnSignals->SetTextRenderColor(FColor::Red);
TurnSignals->SetText(FText::FromString(""));
TurnSignals->SetXScale(1.f);
TurnSignals->SetYScale(1.f);
TurnSignals->SetWorldSize(10); // scale the font with this
TurnSignals->SetVerticalAlignment(EVerticalTextAligment::EVRTA_TextCenter);
TurnSignals->SetHorizontalAlignment(EHorizTextAligment::EHTA_Center);
// Create gear shifter
GearShifter = CreateDefaultSubobject<UTextRenderComponent>(TEXT("GearShifter"));
GearShifter->AttachToComponent(GetRootComponent(), FAttachmentTransformRules::KeepRelativeTransform);
GearShifter->SetRelativeLocation(DashboardLocnInVehicle + FVector(0, 15.f, 0));
GearShifter->SetRelativeRotation(FRotator(0.f, 180.f, 0.f)); // need to flip it to get the text in driver POV
GearShifter->SetTextRenderColor(FColor::Red);
GearShifter->SetText(FText::FromString("D"));
GearShifter->SetXScale(1.f);
GearShifter->SetYScale(1.f);
GearShifter->SetWorldSize(10); // scale the font with this
GearShifter->SetVerticalAlignment(EVerticalTextAligment::EVRTA_TextCenter);
GearShifter->SetHorizontalAlignment(EHorizTextAligment::EHTA_Center);
}
void AEgoVehicle::UpdateDash()
{
// Draw text components
float XPH; // miles-per-hour or km-per-hour
if (EgoSensor->IsReplaying())
{
const DReyeVR::AggregateData *Replay = EgoSensor->GetData();
XPH = Replay->GetVehicleVelocity() * SpeedometerScale; // FwdSpeed is in cm/s
const auto &ReplayInputs = Replay->GetUserInputs();
if (ReplayInputs.ToggledReverse)
PressReverse();
else
ReleaseReverse();
if (bEnableTurnSignalAction)
{
if (ReplayInputs.TurnSignalLeft)
PressTurnSignalL();
else
ReleaseTurnSignalL();
if (ReplayInputs.TurnSignalRight)
PressTurnSignalR();
else
ReleaseTurnSignalR();
}
}
else
{
XPH = GetVehicleForwardSpeed() * SpeedometerScale; // FwdSpeed is in cm/s
}
const FString Data = FString::FromInt(int(FMath::RoundHalfFromZero(XPH)));
Speedometer->SetText(FText::FromString(Data));
if (bEnableTurnSignalAction)
{
// Draw the signals
float Now = GetWorld()->GetTimeSeconds();
const float StartTime = std::max(RightSignalTimeToDie, LeftSignalTimeToDie) - TurnSignalDuration;
FString TurnSignalStr = "";
constexpr static float TurnSignalBlinkRate = 0.4f; // rate of blinking
if (std::fmodf(Now - StartTime, TurnSignalBlinkRate * 2) < TurnSignalBlinkRate)
{
if (Now < RightSignalTimeToDie)
TurnSignalStr = ">>>";
else if (Now < LeftSignalTimeToDie)
TurnSignalStr = "<<<";
}
TurnSignals->SetText(FText::FromString(TurnSignalStr));
}
// Draw the gear shifter
if (bReverse) // backwards
GearShifter->SetText(FText::FromString("R"));
else
GearShifter->SetText(FText::FromString("D"));
}
/// ========================================== ///
/// -----------------:WHEEL:------------------ ///
/// ========================================== ///
void AEgoVehicle::ConstructSteeringWheel()
{
static ConstructorHelpers::FObjectFinder<UStaticMesh> SteeringWheelSM(TEXT(
"StaticMesh'/Game/DReyeVR/EgoVehicle/model3/SteeringWheel/Wheel_StaticMeshl_model3.Wheel_StaticMeshl_model3'"));
SteeringWheel = CreateDefaultSubobject<UStaticMeshComponent>(FName("SteeringWheel"));
SteeringWheel->SetStaticMesh(SteeringWheelSM.Object);
SteeringWheel->SetupAttachment(GetRootComponent()); // The vehicle blueprint itself
SteeringWheel->SetRelativeLocation(InitWheelLocation);
SteeringWheel->SetRelativeRotation(InitWheelRotation);
SteeringWheel->SetGenerateOverlapEvents(false); // don't collide with itself
SteeringWheel->SetCollisionEnabled(ECollisionEnabled::NoCollision);
SteeringWheel->SetVisibility(true);
}
void AEgoVehicle::TickSteeringWheel(const float DeltaTime)
{
const FRotator CurrentRotation = SteeringWheel->GetRelativeRotation();
const float RawSteering = GetVehicleInputs().Steering; // this is scaled in SetSteering
const float TargetAngle = (RawSteering / ScaleSteeringInput) * SteeringAnimScale;
FRotator NewRotation = CurrentRotation;
if (Pawn && Pawn->GetIsLogiConnected())
{
NewRotation.Roll = TargetAngle;
}
else
{
float WheelAngleDeg = GetWheelSteerAngle(EVehicleWheelLocation::Front_Wheel);
// float MaxWheelAngle = GetMaximumSteerAngle();
float DeltaAngle = 10.f * (2.0f * WheelAngleDeg - CurrentRotation.Roll);
// create the new rotation using the deltas
NewRotation += DeltaTime * FRotator(0.f, 0.f, DeltaAngle);
// Clamp the roll amount so the wheel can't spin infinitely
NewRotation.Roll = FMath::Clamp(NewRotation.Roll, -MaxSteerAngleDeg, MaxSteerAngleDeg);
}
SteeringWheel->SetRelativeRotation(NewRotation);
}
/// ========================================== ///
/// -----------------:LEVEL:------------------ ///
/// ========================================== ///
void AEgoVehicle::SetGame(ADReyeVRGameMode *Game)
{
DReyeVRGame = Game;
check(DReyeVRGame != nullptr);
DReyeVRGame->SetEgoVehicle(this);
DReyeVRGame->GetPawn()->BeginEgoVehicle(this, World);
LOG("Successfully assigned GameMode & controller pawn");
}
ADReyeVRGameMode *AEgoVehicle::GetGame()
{
return DReyeVRGame;
}
void AEgoVehicle::TickGame(float DeltaSeconds)
{
if (this->DReyeVRGame != nullptr)
DReyeVRGame->Tick(DeltaSeconds);
}
/// ========================================== ///
/// ---------------:COSMETIC:----------------- ///
/// ========================================== ///
void AEgoVehicle::DebugLines() const
{
#if WITH_EDITOR
if (bDrawDebugEditor)
{
// Calculate gaze data (in world space) using eye tracker data
const DReyeVR::AggregateData *Data = EgoSensor->GetData();
// Compute World positions and orientations
const FRotator &WorldRot = FirstPersonCam->GetComponentRotation();
const FVector &WorldPos = FirstPersonCam->GetComponentLocation();
// First get the gaze origin and direction and vergence from the EyeTracker Sensor
const float RayLength = FMath::Max(1.f, Data->GetGazeVergence() / 100.f); // vergence to m (from cm)
const float VRMeterScale = 100.f;
// Both eyes
const FVector CombinedGaze = RayLength * VRMeterScale * Data->GetGazeDir();
const FVector CombinedOrigin = WorldPos + WorldRot.RotateVector(Data->GetGazeOrigin());
// Left eye
const FVector LeftGaze = RayLength * VRMeterScale * Data->GetGazeDir(DReyeVR::Gaze::LEFT);
const FVector LeftOrigin = WorldPos + WorldRot.RotateVector(Data->GetGazeOrigin(DReyeVR::Gaze::LEFT));
// Right eye
const FVector RightGaze = RayLength * VRMeterScale * Data->GetGazeDir(DReyeVR::Gaze::RIGHT);
const FVector RightOrigin = WorldPos + WorldRot.RotateVector(Data->GetGazeOrigin(DReyeVR::Gaze::RIGHT));
// Use Absolute Ray Position to draw debug information
// Rotate and add the gaze ray to the origin
DrawDebugSphere(World, CombinedOrigin + WorldRot.RotateVector(CombinedGaze), 4.0f, 12, FColor::Blue);
// Draw individual rays for left and right eye
DrawDebugLine(World,
LeftOrigin, // start line
LeftOrigin + 10 * WorldRot.RotateVector(LeftGaze), // end line
FColor::Green, false, -1, 0, 1);
DrawDebugLine(World,
RightOrigin, // start line
RightOrigin + 10 * WorldRot.RotateVector(RightGaze), // end line
FColor::Yellow, false, -1, 0, 1);
}
#endif
}