From e640d6d79f161bed3761080aab0c5430c43c90df Mon Sep 17 00:00:00 2001 From: Meerae Choi Date: Thu, 12 Nov 2026 06:30:35 +0000 Subject: [PATCH 1/2] trivialkart_unreal: Add gamepad and keyboard/mouse input support - Add FTrivialKartGamepadInputProcessor (Slate IInputProcessor) and ATrivialKartPlayerController multi-input mode management for seamless switching across Touch, Gamepad, and Keyboard/Mouse. - Register controller and keyboard gameplay bindings dynamically on a transient runtime clone of IMC_Default with UTrivialKartPositiveTriggerModifier to guard against negative HID (-1.0) and Android DualSense (+0.50) resting trigger values while keeping UE 5.7 asset compatibility. - Add full D-Pad, analog stick (with hysteresis and modal latch), shoulder/Tab tab-switching, BackButton focus, and high-contrast focus visuals across PlayBoardWidget, StoreWidget, GarageWidget, PGSWidget, and SelectableItem. - Configure Android controller/keyboard/mouse runtime settings and device mapping policy in DefaultEngine.ini and DefaultInput.ini, update .gitignore, and document controls in README.md. --- trivialkart/trivialkart_unreal/.gitignore | 5 + .../Config/DefaultEngine.ini | 8 +- .../Config/DefaultInput.ini | 16 + trivialkart/trivialkart_unreal/README.md | 8 +- .../Source/TrivialKart_Unreal.Target.cs | 4 +- .../Private/Actors/TrivialKartHUD.cpp | 299 ++++++- .../TrivialKartGamepadInputProcessor.cpp | 592 ++++++++++++++ .../TrivialKartPlayerController.cpp | 741 +++++++++++++++++- .../Private/Widgets/GarageWidget.cpp | 636 ++++++++++++++- .../Private/Widgets/PGSWidget.cpp | 409 +++++++++- .../Private/Widgets/PlayBoardWidget.cpp | 734 ++++++++++++++++- .../Private/Widgets/SelectableItem.cpp | 250 +++++- .../Private/Widgets/StoreWidget.cpp | 626 ++++++++++++++- .../Public/Actors/TrivialKartHUD.h | 31 +- .../TrivialKartGamepadInputProcessor.h | 74 ++ .../Controllers/TrivialKartPlayerController.h | 101 +++ .../Public/Widgets/GarageWidget.h | 42 +- .../Public/Widgets/PGSWidget.h | 30 +- .../Public/Widgets/PlayBoardWidget.h | 61 +- .../Public/Widgets/SelectableItem.h | 58 +- .../Public/Widgets/StoreWidget.h | 40 +- .../TrivialKart_Unreal.Build.cs | 1 + .../Source/TrivialKart_UnrealEditor.Target.cs | 4 +- 23 files changed, 4627 insertions(+), 143 deletions(-) create mode 100644 trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Controllers/TrivialKartGamepadInputProcessor.cpp create mode 100644 trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Controllers/TrivialKartGamepadInputProcessor.h diff --git a/trivialkart/trivialkart_unreal/.gitignore b/trivialkart/trivialkart_unreal/.gitignore index 6e21aa18..5e081af6 100644 --- a/trivialkart/trivialkart_unreal/.gitignore +++ b/trivialkart/trivialkart_unreal/.gitignore @@ -52,6 +52,7 @@ Plugins/*/Binaries/* # Builds Build/* +Builds/* # Whitelist PakBlacklist-.txt files !Build/*/ @@ -74,3 +75,7 @@ Plugins/*/Intermediate/* # Cache files for the editor to use DerivedDataCache/* +# Local developer collections and personal assets +Content/Developers/* +Content/Collections/* + diff --git a/trivialkart/trivialkart_unreal/Config/DefaultEngine.ini b/trivialkart/trivialkart_unreal/Config/DefaultEngine.ini index effb8fca..11120c36 100644 --- a/trivialkart/trivialkart_unreal/Config/DefaultEngine.ini +++ b/trivialkart/trivialkart_unreal/Config/DefaultEngine.ini @@ -21,7 +21,6 @@ r.Mobile.ShadingPath=1 r.Mobile.AntiAliasing=2 r.Mobile.FloatPrecisionMode=0 r.Mobile.AllowDitheredLODTransition=False -r.Mobile.VirtualTextures=False r.DiscardUnusedQuality=False r.AllowOcclusionQueries=True r.MinScreenRadiusForLights=0.030000 @@ -255,6 +254,11 @@ CommandletClass=Class'/Script/UnrealEd.WorldPartitionConvertCommandlet' bAuthorizeAutomaticWidgetVariableCreation=False FontDPIPreset=Standard FontDPI=72 +RenderFocusRule=Never + +[SystemSettings] +Android.EnableMouse=1 +Android.EnableHardwareKeyboard=1 [/Script/Engine.Engine] +ActiveGameNameRedirects=(OldGameName="TP_Blank",NewGameName="/Script/TrivialKart_Unreal") @@ -379,7 +383,7 @@ GCMClientSenderID= bShowLaunchImage=True bAllowIMU=False bAllowControllers=True -bBlockAndroidKeysOnControllers=False +bBlockAndroidKeysOnControllers=True bControllersBlockDeviceFeedback=False AudioSampleRate=44100 AudioCallbackBufferFrameSize=1024 diff --git a/trivialkart/trivialkart_unreal/Config/DefaultInput.ini b/trivialkart/trivialkart_unreal/Config/DefaultInput.ini index bd574f99..e5f28615 100644 --- a/trivialkart/trivialkart_unreal/Config/DefaultInput.ini +++ b/trivialkart/trivialkart_unreal/Config/DefaultInput.ini @@ -82,3 +82,19 @@ DefaultTouchInterface=None -ConsoleKeys=Tilde +ConsoleKeys=Tilde +[InputPlatformSettings_Android InputPlatformSettings] +input.DeviceMappingPolicy=3 + +[InputPlatformSettings_Mac InputPlatformSettings] +input.DeviceMappingPolicy=3 + +[InputPlatformSettings_Windows InputPlatformSettings] +input.DeviceMappingPolicy=3 + +[InputPlatformSettings_IOS InputPlatformSettings] +input.DeviceMappingPolicy=3 + +[InputPlatformSettings_Linux InputPlatformSettings] +input.DeviceMappingPolicy=3 + + diff --git a/trivialkart/trivialkart_unreal/README.md b/trivialkart/trivialkart_unreal/README.md index 54d2946f..d09dacbc 100644 --- a/trivialkart/trivialkart_unreal/README.md +++ b/trivialkart/trivialkart_unreal/README.md @@ -6,12 +6,13 @@ This version of TrivialKart demonstrates: * **Play Games Services (v2)**: For sign-in, achievements, and cloud save (using Online Subsystem GooglePlay Extension). * **In-App Purchases (IAP)**. +* **Controller & Multi-Input Support**: Seamless runtime switching across Touch, Gamepad (Bluetooth / USB controllers), and Keyboard/Mouse with full UI navigation and visual focus indicators. --- ## Pre-requisites -* **Unreal Engine**: Version 5.4 or higher (Recommended). +* **Unreal Engine**: Version 5.7 or higher (Recommended). * **Android Studio**: Properly configured for the specific version of Unreal Engine being used. * **Google Play Games Unreal Plugin**: Ensure the official plugin is enabled. @@ -24,7 +25,7 @@ This version of TrivialKart demonstrates: ## Getting started 1. Clone the repository and navigate to `trivialkart/trivialkart_unreal`. -2. Right-click `TrivialKart.uproject` and select **Generate Visual Studio project files**. +2. Right-click `TrivialKart_Unreal.uproject` and select **Generate Visual Studio project files**. 3. Open the `.sln` file in Visual Studio (or the `.uproject` in Unreal Editor). 4. Open the `L_TrivialKart` found in `Content/Maps`. @@ -34,7 +35,8 @@ By default, Google Play features are simulated or disabled unless the Google Pla ## Overview -In TrivialKart, the player has a vehicle which they can drive by tapping on it. +In TrivialKart, the player has a vehicle which they can drive by touching and holding on screen, holding a gamepad trigger / `A` / D-Pad Right / Left Stick Right, or holding `Spacebar` / clicking. +Navigate menus (`Garage`, `Play Games Services`, `Store`) using D-Pad or Left Stick, switch tabs with `LB` / `RB` (or `Tab` / `Shift+Tab`), confirm with `A` (`Enter`), and go back with `B` (`Esc` or Android Back). Driving the car uses gas. When the car runs out of gas, to continue driving, more must be purchased using in-game currency. If the player runs out of in-game currency, they may buy more via in-app purchases. diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal.Target.cs b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal.Target.cs index f7b68a32..2ffabcd6 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal.Target.cs +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal.Target.cs @@ -23,8 +23,8 @@ public class TrivialKart_UnrealTarget : TargetRules public TrivialKart_UnrealTarget(TargetInfo Target) : base(Target) { Type = TargetType.Game; - DefaultBuildSettings = BuildSettingsVersion.V6; - IncludeOrderVersion = EngineIncludeOrderVersion.Unreal5_7; + DefaultBuildSettings = BuildSettingsVersion.Latest; + IncludeOrderVersion = EngineIncludeOrderVersion.Latest; ExtraModuleNames.Add("TrivialKart_Unreal"); } } diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Actors/TrivialKartHUD.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Actors/TrivialKartHUD.cpp index 1753ad85..8fe226d8 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Actors/TrivialKartHUD.cpp +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Actors/TrivialKartHUD.cpp @@ -17,14 +17,143 @@ #include "Actors/TrivialKartHUD.h" -#include "Blueprint/UserWidget.h" +#include "Controllers/TrivialKartPlayerController.h" +#include "Engine/Texture2D.h" +#include "TextureResource.h" +#include "Widgets/GarageWidget.h" +#include "Widgets/PGSWidget.h" +#include "Widgets/PlayBoardWidget.h" +#include "Widgets/StoreWidget.h" DEFINE_LOG_CATEGORY(LogTemplateHUD); +namespace +{ + float DistToSegment2D(float Px, float Py, float Ax, float Ay, float Bx, float By) + { + const float Vx = Bx - Ax; + const float Vy = By - Ay; + const float Wx = Px - Ax; + const float Wy = Py - Ay; + const float C1 = Wx * Vx + Wy * Vy; + if (C1 <= 0.0f) + { + return FMath::Sqrt(Wx * Wx + Wy * Wy); + } + const float C2 = Vx * Vx + Vy * Vy; + if (C2 <= C1) + { + const float Dx = Px - Bx; + const float Dy = Py - By; + return FMath::Sqrt(Dx * Dx + Dy * Dy); + } + const float T = C1 / C2; + const float ProjX = Ax + T * Vx; + const float ProjY = Ay + T * Vy; + const float Dx = Px - ProjX; + const float Dy = Py - ProjY; + return FMath::Sqrt(Dx * Dx + Dy * Dy); + } + + UTexture2D* BuildProceduralTouchHandTexture() + { + constexpr int32 Size = 96; + UTexture2D* Texture = UTexture2D::CreateTransient(Size, Size, PF_B8G8R8A8); + if (!Texture || !Texture->GetPlatformData() || Texture->GetPlatformData()->Mips.Num() == 0) + { + return nullptr; + } + Texture->SRGB = true; + Texture->Filter = TF_Bilinear; + + FTexture2DMipMap& Mip = Texture->GetPlatformData()->Mips[0]; + uint8* Pixels = static_cast(Mip.BulkData.Lock(LOCK_READ_WRITE)); + if (!Pixels) + { + return nullptr; + } + + for (int32 Y = 0; Y < Size; ++Y) + { + for (int32 X = 0; X < Size; ++X) + { + const float Px = static_cast(X) + 0.5f; + const float Py = static_cast(Y) + 0.5f; + + const float DIndex = DistToSegment2D(Px, Py, 44.0f, 26.0f, 44.0f, 58.0f) - 6.2f; + const float DMiddle = DistToSegment2D(Px, Py, 55.5f, 43.0f, 55.5f, 60.0f) - 5.4f; + const float DRing = DistToSegment2D(Px, Py, 66.0f, 47.0f, 66.0f, 62.0f) - 5.1f; + const float DPinky = DistToSegment2D(Px, Py, 75.5f, 52.0f, 74.0f, 66.0f) - 4.7f; + const float DThumb = DistToSegment2D(Px, Py, 28.0f, 54.0f, 42.0f, 68.0f) - 5.8f; + const float DPalmUpper = DistToSegment2D(Px, Py, 44.0f, 58.0f, 69.0f, 63.0f) - 12.5f; + const float DPalmLower = DistToSegment2D(Px, Py, 48.0f, 69.0f, 61.0f, 72.0f) - 14.5f; + + float HandDist = FMath::Min(DIndex, DMiddle); + HandDist = FMath::Min(HandDist, DRing); + HandDist = FMath::Min(HandDist, DPinky); + HandDist = FMath::Min(HandDist, DThumb); + HandDist = FMath::Min(HandDist, DPalmUpper); + HandDist = FMath::Min(HandDist, DPalmLower); + + const float DGroove1 = DistToSegment2D(Px, Py, 50.0f, 41.0f, 50.0f, 53.0f); + const float DGroove2 = DistToSegment2D(Px, Py, 61.0f, 45.0f, 61.0f, 55.0f); + const float DGroove3 = DistToSegment2D(Px, Py, 71.0f, 50.0f, 71.0f, 58.0f); + const float GrooveDist = FMath::Min(DGroove1, FMath::Min(DGroove2, DGroove3)); + + const float TipDist = FVector2D::Distance(FVector2D(Px, Py), FVector2D(44.0f, 24.0f)); + float RippleDist = 100.0f; + if (Py < 31.0f) + { + const float InnerRing = FMath::Abs(TipDist - 13.5f) - 1.6f; + const float OuterRing = (Py < 25.0f) ? (FMath::Abs(TipDist - 20.5f) - 1.5f) : 100.0f; + RippleDist = FMath::Min(InnerRing, OuterRing); + } + + FLinearColor OutColor(0.0f, 0.0f, 0.0f, 0.0f); + + if (RippleDist < 1.0f && HandDist > 1.5f) + { + const float RippleAlpha = FMath::Clamp(1.0f - RippleDist, 0.0f, 1.0f); + OutColor = FLinearColor(1.0f, 0.86f, 0.22f, RippleAlpha * 0.95f); + } + + if (HandDist < 2.2f) + { + const float OuterAlpha = FMath::Clamp(2.2f - HandDist, 0.0f, 1.0f); + const float FillFactor = FMath::Clamp(0.5f - HandDist, 0.0f, 1.0f); + const float GrooveFactor = (HandDist < -1.0f) ? FMath::Clamp(1.4f - GrooveDist, 0.0f, 1.0f) : 0.0f; + + const FLinearColor OutlineColor(0.05f, 0.08f, 0.16f, 1.0f); + const FLinearColor FillColor(1.0f, 0.97f, 0.88f, 1.0f); + FLinearColor HandColor = FMath::Lerp(OutlineColor, FillColor, FillFactor * (1.0f - GrooveFactor * 0.85f)); + HandColor.A = OuterAlpha; + OutColor = HandColor; + } + + const int32 Idx = (Y * Size + X) * 4; + Pixels[Idx + 0] = static_cast(FMath::Clamp(OutColor.B * 255.0f, 0.0f, 255.0f)); + Pixels[Idx + 1] = static_cast(FMath::Clamp(OutColor.G * 255.0f, 0.0f, 255.0f)); + Pixels[Idx + 2] = static_cast(FMath::Clamp(OutColor.R * 255.0f, 0.0f, 255.0f)); + Pixels[Idx + 3] = static_cast(FMath::Clamp(OutColor.A * 255.0f, 0.0f, 255.0f)); + } + } + + Mip.BulkData.Unlock(); + Texture->UpdateResource(); + return Texture; + } +} + +bool ATrivialKartHUD::IsSubMenuWidgetType(EWidgetType WidgetType) +{ + return WidgetType == EWidgetType::Garage + || WidgetType == EWidgetType::PGS + || WidgetType == EWidgetType::Store; +} + void ATrivialKartHUD::BeginPlay() { Super::BeginPlay(); - AddWidgetToScreen(EWidgetType::Loading, 10); AddWidgetToScreen(EWidgetType::PlayBoard); } @@ -32,39 +161,187 @@ void ATrivialKartHUD::AddWidgetToScreen(const EWidgetType WidgetType, int32 ZOrd { #if WITH_EDITOR if (WidgetType == EWidgetType::Loading) + { return; + } #endif + + if (GetActiveWidget(WidgetType) != nullptr) + { + return; + } + + if (IsSubMenuWidgetType(WidgetType) && IsSubMenuOpen()) + { + return; + } + if (!WidgetTemplates.Contains(WidgetType)) { -UE_LOG(LogTemplateHUD, Warning, TEXT("Widget template does not exist")); + UE_LOG(LogTemplateHUD, Warning, TEXT("Widget template does not exist")); return; } - const TWeakObjectPtr CurrentWidget = CreateWidget(GetOwningPlayerController(), - WidgetTemplates[WidgetType]); + + const TWeakObjectPtr CurrentWidget = CreateWidget(GetOwningPlayerController(), WidgetTemplates[WidgetType]); if (CurrentWidget.IsValid()) { CurrentWidget->AddToViewport(ZOrder); ActiveWidgets.Emplace(WidgetType, CurrentWidget); + SyncGameplayInputContext(); + + if (ATrivialKartPlayerController* PlayerController = Cast(GetOwningPlayerController())) + { + PlayerController->LatchStickUntilNeutral(); + PlayerController->RestoreFocusToGameViewport(); + } } } void ATrivialKartHUD::RemoveWidgetFromScreen(const EWidgetType WidgetType) { - if (!ActiveWidgets.Contains(WidgetType)) + const TWeakObjectPtr* ExistingPtr = ActiveWidgets.Find(WidgetType); + if (!ExistingPtr) { UE_LOG(LogTemplateHUD, Warning, TEXT("Widget is not on Screen")); return; } - ActiveWidgets[WidgetType]->RemoveFromParent(); + if (UUserWidget* ExistingWidget = ExistingPtr->Get()) + { + ExistingWidget->RemoveFromParent(); + } ActiveWidgets.Remove(WidgetType); + SyncGameplayInputContext(); + + if (ATrivialKartPlayerController* PlayerController = Cast(GetOwningPlayerController())) + { + PlayerController->LatchStickUntilNeutral(); + PlayerController->RestoreFocusToGameViewport(); + } } UUserWidget* ATrivialKartHUD::GetWidgetOfType(const EWidgetType WidgetType) { - if (!ActiveWidgets.Contains(WidgetType)) + if (UUserWidget* ActiveWidget = GetActiveWidget(WidgetType)) + { + return ActiveWidget; + } + return nullptr; +} + +bool ATrivialKartHUD::HandleGamepadKey(const FKey& Key, bool bIsPressed, bool bIsRepeat) +{ + if (UStoreWidget* Store = GetActiveWidget(EWidgetType::Store)) + { + return Store->HandleGamepadKey(Key, bIsPressed); + } + if (UGarageWidget* Garage = GetActiveWidget(EWidgetType::Garage)) + { + return Garage->HandleGamepadKey(Key, bIsPressed); + } + if (UPGSWidget* PGS = GetActiveWidget(EWidgetType::PGS)) + { + return PGS->HandleGamepadKey(Key, bIsPressed); + } + if (UPlayBoardWidget* PlayBoard = GetActiveWidget(EWidgetType::PlayBoard)) + { + return PlayBoard->HandleGamepadKey(Key, bIsPressed, bIsRepeat); + } + return false; +} + +bool ATrivialKartHUD::IsSubMenuOpen() const +{ + return GetActiveWidget(EWidgetType::Store) != nullptr + || GetActiveWidget(EWidgetType::Garage) != nullptr + || GetActiveWidget(EWidgetType::PGS) != nullptr; +} + +bool ATrivialKartHUD::IsUIBlockingInput() const +{ + if (IsSubMenuOpen()) + { + return true; + } + const UPlayBoardWidget* PlayBoard = GetActiveWidget(EWidgetType::PlayBoard); + return PlayBoard && PlayBoard->HasBlockingMenuFocus(); +} + +bool ATrivialKartHUD::IsStickNavigationEnabled() const +{ + if (IsSubMenuOpen()) + { + return true; + } + const ATrivialKartPlayerController* PC = Cast(GetOwningPlayerController()); + if (!PC || PC->GetActiveInputMode() != ETrivialKartInputMode::Gamepad) + { + return false; + } + const UPlayBoardWidget* PlayBoard = GetActiveWidget(EWidgetType::PlayBoard); + return PlayBoard != nullptr; +} + +void ATrivialKartHUD::SyncGameplayInputContext() const +{ + if (ATrivialKartPlayerController* PlayerController = Cast(GetOwningPlayerController())) + { + PlayerController->SetGameplayInputEnabled(!IsUIBlockingInput()); + } +} + +void ATrivialKartHUD::ClearPlayBoardMenuFocus() +{ + if (UPlayBoardWidget* PlayBoard = GetActiveWidget(EWidgetType::PlayBoard)) + { + PlayBoard->ClearMenuFocus(false); + } +} + +void ATrivialKartHUD::NotifyViewportPointerDown(const FVector2D& ScreenSpacePosition) +{ + if (UPlayBoardWidget* PlayBoard = GetActiveWidget(EWidgetType::PlayBoard)) + { + PlayBoard->OnViewportPointerDown(ScreenSpacePosition); + } +} + +void ATrivialKartHUD::CancelPendingPresses() +{ + if (UStoreWidget* Store = GetActiveWidget(EWidgetType::Store)) + { + Store->CancelPendingPress(); + } + if (UGarageWidget* Garage = GetActiveWidget(EWidgetType::Garage)) + { + Garage->CancelPendingPress(); + } + if (UPGSWidget* PGS = GetActiveWidget(EWidgetType::PGS)) + { + PGS->CancelPendingPress(); + } + if (UPlayBoardWidget* PlayBoard = GetActiveWidget(EWidgetType::PlayBoard)) + { + PlayBoard->CancelPendingPress(); + } +} + +void ATrivialKartHUD::RefreshActiveSubMenu() +{ + if (UStoreWidget* Store = GetActiveWidget(EWidgetType::Store)) + { + Store->RefreshOwnershipAndFocus(false); + } + if (UGarageWidget* Garage = GetActiveWidget(EWidgetType::Garage)) + { + Garage->RefreshOwnershipAndFocus(false); + } +} + +UTexture2D* ATrivialKartHUD::GetOrCreateTouchHandTexture() +{ + if (!IsValid(CachedTouchHandTexture)) { - UE_LOG(LogTemplateHUD, Warning, TEXT("Active widget does not exist")); - return nullptr; + CachedTouchHandTexture = BuildProceduralTouchHandTexture(); } - return ActiveWidgets[WidgetType].Get(); + return CachedTouchHandTexture; } diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Controllers/TrivialKartGamepadInputProcessor.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Controllers/TrivialKartGamepadInputProcessor.cpp new file mode 100644 index 00000000..48519afc --- /dev/null +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Controllers/TrivialKartGamepadInputProcessor.cpp @@ -0,0 +1,592 @@ +/* +* Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "Controllers/TrivialKartGamepadInputProcessor.h" + +#include "Controllers/TrivialKartPlayerController.h" +#include "Framework/Application/SlateApplication.h" +#include "HAL/PlatformTime.h" +#include "Input/Events.h" + +namespace +{ + constexpr float StickActivateThreshold = 0.60f; + constexpr float StickReleaseThreshold = 0.35f; + constexpr float StickDominanceRatio = 1.25f; + constexpr float GamepadModeStickThreshold = 0.45f; + constexpr float GamepadTriggerActiveThreshold = 0.65f; + constexpr float StickInitialRepeatDelay = 0.35f; + constexpr float StickRepeatInterval = 0.11f; + constexpr float MouseWakeTravelDefaultSq = 16.0f; + constexpr float MouseWakeTravelFromGamepadSq = 4096.0f; + constexpr double GamepadTouchpadGuardSeconds = 0.25; + + bool IsAndroidPassthroughSystemKey(const FKey& Key) + { + return Key == EKeys::Android_Volume_Up + || Key == EKeys::Android_Volume_Down + || Key == EKeys::Android_Menu; + } + + bool IsSlateNavigationLeakKey(const FKey& Key) + { + return Key == EKeys::Gamepad_LeftStick_Up + || Key == EKeys::Gamepad_LeftStick_Down + || Key == EKeys::Gamepad_LeftStick_Left + || Key == EKeys::Gamepad_LeftStick_Right + || Key == EKeys::Gamepad_DPad_Up + || Key == EKeys::Gamepad_DPad_Down + || Key == EKeys::Gamepad_DPad_Left + || Key == EKeys::Gamepad_DPad_Right + || Key == EKeys::Up + || Key == EKeys::Down + || Key == EKeys::Left + || Key == EKeys::Right + || Key == EKeys::Tab + || Key == EKeys::SpaceBar + || Key == EKeys::Enter; + } + + bool IsGamepadTriggerAxis(const FKey& Key) + { + return Key == EKeys::Gamepad_LeftTriggerAxis + || Key == EKeys::Gamepad_RightTriggerAxis; + } + + bool IsGenuineKeyboardKey(const FKey& Key) + { + if (!Key.IsValid() || Key.IsGamepadKey() || Key.IsTouch() || Key.IsMouseButton() || Key.IsAxis1D() || Key.IsAxis2D()) + { + return false; + } + const FString KeyName = Key.GetFName().ToString(); + if (KeyName.StartsWith(TEXT("Android_")) || KeyName.StartsWith(TEXT("Steam_")) || KeyName.StartsWith(TEXT("Gesture_"))) + { + return false; + } + return true; + } +} + +FTrivialKartGamepadInputProcessor::FTrivialKartGamepadInputProcessor(ATrivialKartPlayerController* InOwner) + : OwnerController(InOwner) +{ + if (FSlateApplication::IsInitialized()) + { + AppActivationHandle = FSlateApplication::Get().OnApplicationActivationStateChanged().AddRaw( + this, &FTrivialKartGamepadInputProcessor::OnApplicationActivationChanged); + } +} + +FTrivialKartGamepadInputProcessor::~FTrivialKartGamepadInputProcessor() +{ + if (AppActivationHandle.IsValid() && FSlateApplication::IsInitialized()) + { + FSlateApplication::Get().OnApplicationActivationStateChanged().Remove(AppActivationHandle); + AppActivationHandle.Reset(); + } +} + +void FTrivialKartGamepadInputProcessor::ResetAnalogState() +{ + CachedLeftX = 0.0f; + CachedLeftY = 0.0f; + CachedLeftTrigger = 0.0f; + CachedRightTrigger = 0.0f; + ActiveStickDir = ETrivialKartStickDir::None; + StickRepeatRemaining = 0.0f; + bLatchUntilNeutral = false; + + if (OwnerController.IsValid()) + { + OwnerController->CancelPendingPresses(); + } +} + +void FTrivialKartGamepadInputProcessor::ResetState() +{ + ConsumedPressedKeys.Empty(); + HeldPhysicalKeys.Empty(); + LatchedRepeatKeys.Empty(); + AccumulatedMouseDelta = FVector2D::ZeroVector; + ResetAnalogState(); +} + +void FTrivialKartGamepadInputProcessor::LatchStickUntilNeutral() +{ + ActiveStickDir = ETrivialKartStickDir::None; + StickRepeatRemaining = 0.0f; + LatchedRepeatKeys = HeldPhysicalKeys; + if (FMath::Abs(CachedLeftX) >= StickReleaseThreshold || FMath::Abs(CachedLeftY) >= StickReleaseThreshold) + { + bLatchUntilNeutral = true; + } +} + +void FTrivialKartGamepadInputProcessor::OnApplicationActivationChanged(const bool bIsActive) +{ + if (!bIsActive) + { + ResetState(); + } +} + +ETrivialKartStickDir FTrivialKartGamepadInputProcessor::ComputeDesiredStickDir() const +{ + const float AbsX = FMath::Abs(CachedLeftX); + const float AbsY = FMath::Abs(CachedLeftY); + + if (ActiveStickDir == ETrivialKartStickDir::Left || ActiveStickDir == ETrivialKartStickDir::Right) + { + if (AbsY >= StickActivateThreshold && AbsY > AbsX * StickDominanceRatio) + { + return CachedLeftY > 0.0f ? ETrivialKartStickDir::Up : ETrivialKartStickDir::Down; + } + if (ActiveStickDir == ETrivialKartStickDir::Right && CachedLeftX <= -StickActivateThreshold) + { + return ETrivialKartStickDir::Left; + } + if (ActiveStickDir == ETrivialKartStickDir::Left && CachedLeftX >= StickActivateThreshold) + { + return ETrivialKartStickDir::Right; + } + if ((ActiveStickDir == ETrivialKartStickDir::Right && CachedLeftX >= StickReleaseThreshold) || + (ActiveStickDir == ETrivialKartStickDir::Left && CachedLeftX <= -StickReleaseThreshold)) + { + return ActiveStickDir; + } + } + else if (ActiveStickDir == ETrivialKartStickDir::Up || ActiveStickDir == ETrivialKartStickDir::Down) + { + if (AbsX >= StickActivateThreshold && AbsX > AbsY * StickDominanceRatio) + { + return CachedLeftX > 0.0f ? ETrivialKartStickDir::Right : ETrivialKartStickDir::Left; + } + if (ActiveStickDir == ETrivialKartStickDir::Up && CachedLeftY <= -StickActivateThreshold) + { + return ETrivialKartStickDir::Down; + } + if (ActiveStickDir == ETrivialKartStickDir::Down && CachedLeftY >= StickActivateThreshold) + { + return ETrivialKartStickDir::Up; + } + if ((ActiveStickDir == ETrivialKartStickDir::Up && CachedLeftY >= StickReleaseThreshold) || + (ActiveStickDir == ETrivialKartStickDir::Down && CachedLeftY <= -StickReleaseThreshold)) + { + return ActiveStickDir; + } + } + + if (AbsX >= StickActivateThreshold && AbsX >= AbsY * StickDominanceRatio) + { + return CachedLeftX > 0.0f ? ETrivialKartStickDir::Right : ETrivialKartStickDir::Left; + } + if (AbsY >= StickActivateThreshold && AbsY >= AbsX * StickDominanceRatio) + { + return CachedLeftY > 0.0f ? ETrivialKartStickDir::Up : ETrivialKartStickDir::Down; + } + return ETrivialKartStickDir::None; +} + +FKey FTrivialKartGamepadInputProcessor::StickDirToKey(ETrivialKartStickDir Dir) +{ + switch (Dir) + { + case ETrivialKartStickDir::Up: + return EKeys::Gamepad_DPad_Up; + case ETrivialKartStickDir::Down: + return EKeys::Gamepad_DPad_Down; + case ETrivialKartStickDir::Left: + return EKeys::Gamepad_DPad_Left; + case ETrivialKartStickDir::Right: + return EKeys::Gamepad_DPad_Right; + default: + return EKeys::Invalid; + } +} + +void FTrivialKartGamepadInputProcessor::Tick(const float DeltaTime, FSlateApplication& SlateApp, TSharedRef Cursor) +{ + if (!OwnerController.IsValid()) + { + return; + } + +#if WITH_EDITOR + if (!OwnerController->IsGameViewportFocused()) + { + if (ActiveStickDir != ETrivialKartStickDir::None || ConsumedPressedKeys.Num() > 0) + { + ResetState(); + } + return; + } +#endif + + if (bLatchUntilNeutral) + { + if (FMath::Abs(CachedLeftX) < StickReleaseThreshold && FMath::Abs(CachedLeftY) < StickReleaseThreshold) + { + bLatchUntilNeutral = false; + } + else + { + ActiveStickDir = ETrivialKartStickDir::None; + StickRepeatRemaining = 0.0f; + return; + } + } + + if (!OwnerController->IsStickNavigationEnabled()) + { + ActiveStickDir = ETrivialKartStickDir::None; + StickRepeatRemaining = 0.0f; + return; + } + + const ETrivialKartStickDir DesiredDir = ComputeDesiredStickDir(); + if (DesiredDir == ETrivialKartStickDir::None) + { + ActiveStickDir = ETrivialKartStickDir::None; + StickRepeatRemaining = 0.0f; + return; + } + + // On PlayBoard when menu focus is inactive, allow Left Stick Up/Down to enter the bottom menu while Left Stick Right continues driving + if (!OwnerController->IsUIBlockingInput() && + (DesiredDir == ETrivialKartStickDir::Left || DesiredDir == ETrivialKartStickDir::Right)) + { + ActiveStickDir = ETrivialKartStickDir::None; + StickRepeatRemaining = 0.0f; + return; + } + + if (DesiredDir != ActiveStickDir) + { + ActiveStickDir = DesiredDir; + StickRepeatRemaining = StickInitialRepeatDelay; + const FKey MappedKey = StickDirToKey(ActiveStickDir); + if (MappedKey.IsValid()) + { + OwnerController->HandleGamepadKey(MappedKey, true, false); + } + return; + } + + StickRepeatRemaining -= DeltaTime; + if (StickRepeatRemaining <= 0.0f) + { + StickRepeatRemaining = StickRepeatInterval; + const FKey MappedKey = StickDirToKey(ActiveStickDir); + if (MappedKey.IsValid()) + { + OwnerController->HandleGamepadKey(MappedKey, true, true); + } + } +} + +bool FTrivialKartGamepadInputProcessor::HandleKeyDownEvent(FSlateApplication& SlateApp, const FKeyEvent& InKeyEvent) +{ + return ProcessKeyEvent(InKeyEvent, true); +} + +bool FTrivialKartGamepadInputProcessor::HandleKeyUpEvent(FSlateApplication& SlateApp, const FKeyEvent& InKeyEvent) +{ + return ProcessKeyEvent(InKeyEvent, false); +} + +bool FTrivialKartGamepadInputProcessor::HandleAnalogInputEvent(FSlateApplication& SlateApp, const FAnalogInputEvent& InAnalogInputEvent) +{ + if (!OwnerController.IsValid()) + { + return false; + } + + const FKey Key = InAnalogInputEvent.GetKey(); + if (!OwnerController->ShouldAcceptInputFromUser(InAnalogInputEvent.GetUserIndex(), Key.IsGamepadKey())) + { + return false; + } + +#if WITH_EDITOR + if (!OwnerController->IsGameViewportFocused()) + { + return false; + } +#endif + + const float Value = InAnalogInputEvent.GetAnalogValue(); + const float AbsValue = FMath::Abs(Value); + + if (Key == EKeys::Gamepad_LeftX) + { + CachedLeftX = Value; + } + else if (Key == EKeys::Gamepad_LeftY) + { + CachedLeftY = Value; + } + else if (Key == EKeys::Gamepad_LeftTriggerAxis) + { + CachedLeftTrigger = Value; + } + else if (Key == EKeys::Gamepad_RightTriggerAxis) + { + CachedRightTrigger = Value; + } + + const bool bIsStickActive = (Key == EKeys::Gamepad_LeftX || Key == EKeys::Gamepad_LeftY) && (AbsValue >= GamepadModeStickThreshold); + // Use signed Value >= 0.65f for triggers so DualSense Android 12+ resting +0.50f and legacy HID resting -1.0f never false-trigger + const bool bIsTriggerPulled = IsGamepadTriggerAxis(Key) && (Value >= GamepadTriggerActiveThreshold); + + if (bIsStickActive || bIsTriggerPulled) + { + LastGamepadActivityTimeSeconds = FPlatformTime::Seconds(); + AccumulatedMouseDelta = FVector2D::ZeroVector; + OwnerController->NotifyExplicitDeviceInput(ETrivialKartInputMode::Gamepad); + + if (bIsTriggerPulled && !OwnerController->IsSubMenuOpen()) + { + OwnerController->ClearPlayBoardMenuFocus(); + } + } + + if (OwnerController->IsUIBlockingInput() && (Key == EKeys::Gamepad_LeftX || Key == EKeys::Gamepad_LeftY) && AbsValue >= 0.20f) + { + return true; + } + + return false; +} + +bool FTrivialKartGamepadInputProcessor::HandleMouseButtonDownEvent(FSlateApplication& SlateApp, const FPointerEvent& MouseEvent) +{ + if (!OwnerController.IsValid()) + { + return false; + } + +#if WITH_EDITOR + if (!OwnerController->IsScreenPositionInGameViewport(MouseEvent.GetScreenSpacePosition())) + { + return false; + } +#endif + + AccumulatedMouseDelta = FVector2D::ZeroVector; + OwnerController->NotifyPointerDeviceInput(MouseEvent.IsTouchEvent() + ? ETrivialKartInputMode::Touch + : ETrivialKartInputMode::KeyboardMouse); + OwnerController->NotifyViewportPointerDown(MouseEvent.GetScreenSpacePosition()); + return false; +} + +bool FTrivialKartGamepadInputProcessor::HandleMouseButtonUpEvent(FSlateApplication& SlateApp, const FPointerEvent& MouseEvent) +{ + return false; +} + +bool FTrivialKartGamepadInputProcessor::HandleMouseMoveEvent(FSlateApplication& SlateApp, const FPointerEvent& MouseEvent) +{ + if (OwnerController.IsValid() && !MouseEvent.IsTouchEvent()) + { +#if WITH_EDITOR + if (!OwnerController->IsScreenPositionInGameViewport(MouseEvent.GetScreenSpacePosition())) + { + return false; + } +#endif +#if PLATFORM_ANDROID + // DualSense / DualShock 4 controllers on Android expose their touchpad as a cursor device; require a click rather than cursor drift while a gamepad is attached + if (OwnerController->IsGamepadAttached() && OwnerController->GetActiveInputMode() == ETrivialKartInputMode::Gamepad) + { + AccumulatedMouseDelta = FVector2D::ZeroVector; + return false; + } +#endif + // Guard against accidental thumb grazes on DualSense / DualShock 4 built-in touchpads while actively using gamepad + if ((FPlatformTime::Seconds() - LastGamepadActivityTimeSeconds) < GamepadTouchpadGuardSeconds) + { + AccumulatedMouseDelta = FVector2D::ZeroVector; + return false; + } + + const float RequiredTravelSq = (OwnerController->GetActiveInputMode() == ETrivialKartInputMode::Gamepad) + ? MouseWakeTravelFromGamepadSq + : MouseWakeTravelDefaultSq; + + AccumulatedMouseDelta += MouseEvent.GetCursorDelta(); + if (AccumulatedMouseDelta.SizeSquared() >= RequiredTravelSq) + { + AccumulatedMouseDelta = FVector2D::ZeroVector; + OwnerController->NotifyPointerDeviceInput(ETrivialKartInputMode::KeyboardMouse); + } + } + return false; +} + +bool FTrivialKartGamepadInputProcessor::ProcessKeyEvent(const FKeyEvent& InKeyEvent, bool bIsPressed) +{ + if (!OwnerController.IsValid()) + { + return false; + } + + const FKey RawKey = InKeyEvent.GetKey(); + if (IsAndroidPassthroughSystemKey(RawKey)) + { + return false; + } + + if (!OwnerController->ShouldAcceptInputFromUser(InKeyEvent.GetUserIndex(), RawKey.IsGamepadKey())) + { + return false; + } + +#if WITH_EDITOR + if (!OwnerController->IsGameViewportFocused()) + { + if (!bIsPressed) + { + ConsumedPressedKeys.Remove(RawKey); + HeldPhysicalKeys.Remove(RawKey); + LatchedRepeatKeys.Remove(RawKey); + } + return false; + } +#endif + + // Block premature digital trigger keys synthesized on Android DualSense (+0.50f resting) before real trigger travel (>= 0.65f) + if (RawKey == EKeys::Gamepad_LeftTrigger || RawKey == EKeys::Gamepad_RightTrigger) + { + const float CachedAxis = (RawKey == EKeys::Gamepad_LeftTrigger) ? CachedLeftTrigger : CachedRightTrigger; + if (bIsPressed && CachedAxis < GamepadTriggerActiveThreshold) + { + return true; + } + } + + // Analog thumbstick UI navigation (with hysteresis, axis dominance, and neutral latch) is driven from Tick(). + // Swallow Slate's low-threshold synthesized digital stick keys during UI navigation so they never double-fire + // or trigger gameplay ClearPlayBoardMenuFocus() when moving Left/Right across HUD menu buttons. + const bool bIsSynthesizedStickMenuKey = + RawKey == EKeys::Gamepad_LeftStick_Up + || RawKey == EKeys::Gamepad_LeftStick_Down + || RawKey == EKeys::Gamepad_LeftStick_Left + || (RawKey == EKeys::Gamepad_LeftStick_Right && OwnerController->IsUIBlockingInput()); + + if (bIsSynthesizedStickMenuKey || (!bIsPressed && RawKey == EKeys::Gamepad_LeftStick_Right && ConsumedPressedKeys.Contains(RawKey))) + { + if (bIsPressed) + { + LastGamepadActivityTimeSeconds = FPlatformTime::Seconds(); + AccumulatedMouseDelta = FVector2D::ZeroVector; + OwnerController->NotifyExplicitDeviceInput(ETrivialKartInputMode::Gamepad); + ConsumedPressedKeys.Add(RawKey); + return true; + } + const bool bWasConsumed = ConsumedPressedKeys.Remove(RawKey) > 0; + return (RawKey != EKeys::Gamepad_LeftStick_Right) || bWasConsumed; + } + + if (RawKey == EKeys::Android_Back) + { + if (bIsPressed) + { + if (!InKeyEvent.IsRepeat()) + { + HeldPhysicalKeys.Add(RawKey); + LatchedRepeatKeys.Remove(RawKey); + } + if (InKeyEvent.IsRepeat() && (ConsumedPressedKeys.Contains(RawKey) || LatchedRepeatKeys.Contains(RawKey))) + { + return true; + } + if (!OwnerController->IsUIBlockingInput()) + { + return false; + } + if (InKeyEvent.IsRepeat()) + { + return true; + } + const bool bHandled = OwnerController->HandleUICancelKey(true); + if (bHandled) + { + ConsumedPressedKeys.Add(RawKey); + } + return bHandled; + } + + HeldPhysicalKeys.Remove(RawKey); + LatchedRepeatKeys.Remove(RawKey); + const bool bWasConsumed = ConsumedPressedKeys.Remove(RawKey) > 0; + const bool bHandled = bWasConsumed ? OwnerController->HandleUICancelKey(false) : false; + return bHandled || bWasConsumed; + } + + if (bIsPressed) + { + if (!InKeyEvent.IsRepeat()) + { + HeldPhysicalKeys.Add(RawKey); + LatchedRepeatKeys.Remove(RawKey); + } + + if (RawKey.IsGamepadKey()) + { + LastGamepadActivityTimeSeconds = FPlatformTime::Seconds(); + AccumulatedMouseDelta = FVector2D::ZeroVector; + OwnerController->NotifyExplicitDeviceInput(ETrivialKartInputMode::Gamepad); + } + else if (IsGenuineKeyboardKey(RawKey)) + { + OwnerController->NotifyExplicitDeviceInput(ETrivialKartInputMode::KeyboardMouse); + } + + if (InKeyEvent.IsRepeat() && LatchedRepeatKeys.Contains(RawKey)) + { + return true; + } + + if (InKeyEvent.IsRepeat() && ConsumedPressedKeys.Contains(RawKey) && !OwnerController->IsUIBlockingInput()) + { + return true; + } + + const bool bHandled = OwnerController->HandleGamepadKey(RawKey, true, InKeyEvent.IsRepeat(), InKeyEvent.IsShiftDown()); + // Prevent Enter or Tab from ever triggering an invisible Slate widget click when custom focus is inactive + const bool bBlockUnfocusedActivationLeak = (RawKey == EKeys::Enter || RawKey == EKeys::Tab); + const bool bBlockSlateLeak = (OwnerController->IsUIBlockingInput() && IsSlateNavigationLeakKey(RawKey)) || bBlockUnfocusedActivationLeak; + if (bHandled || bBlockSlateLeak) + { + ConsumedPressedKeys.Add(RawKey); + return true; + } + + if (RawKey == EKeys::SpaceBar) + { + OwnerController->RestoreFocusToGameViewport(); + } + return false; + } + + HeldPhysicalKeys.Remove(RawKey); + LatchedRepeatKeys.Remove(RawKey); + const bool bWasConsumed = ConsumedPressedKeys.Remove(RawKey) > 0; + const bool bHandled = OwnerController->HandleGamepadKey(RawKey, false, false, InKeyEvent.IsShiftDown()); + return bHandled || bWasConsumed; +} diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Controllers/TrivialKartPlayerController.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Controllers/TrivialKartPlayerController.cpp index 7c0322e3..acaba458 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Controllers/TrivialKartPlayerController.cpp +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Controllers/TrivialKartPlayerController.cpp @@ -14,25 +14,754 @@ * limitations under the License. */ - #include "Controllers/TrivialKartPlayerController.h" +#include "Actors/TrivialKartHUD.h" +#include "Async/Async.h" +#include "Controllers/TrivialKartGamepadInputProcessor.h" +#include "Engine/GameInstance.h" +#include "Engine/GameViewportClient.h" +#include "Engine/LocalPlayer.h" +#include "EnhancedActionKeyMapping.h" #include "EnhancedInputSubsystems.h" +#include "Framework/Application/SlateApplication.h" +#include "GenericPlatform/GenericApplication.h" +#include "GenericPlatform/GenericPlatformInputDeviceMapper.h" +#include "HAL/PlatformTime.h" +#include "InputAction.h" +#include "InputActionValue.h" +#include "InputMappingContext.h" +#include "UObject/ConstructorHelpers.h" +#include "Widgets/SViewport.h" +#include "Widgets/SWidget.h" + +FInputActionValue UTrivialKartPositiveTriggerModifier::ModifyRaw_Implementation( + const UEnhancedPlayerInput* PlayerInput, + FInputActionValue CurrentValue, + float DeltaTime) +{ + const float RawAxis = CurrentValue.Get(); + if (RawAxis >= ActiveThreshold) + { + return CurrentValue; + } + return FInputActionValue(CurrentValue.GetValueType(), FVector::ZeroVector); +} ATrivialKartPlayerController::ATrivialKartPlayerController() { - bShowMouseCursor = true; + bShowMouseCursor = (ActiveInputMode == ETrivialKartInputMode::KeyboardMouse); + bEnableClickEvents = true; + bEnableMouseOverEvents = true; + bEnableTouchEvents = true; + bEnableTouchOverEvents = true; + + static ConstructorHelpers::FObjectFinder DefaultMCFinder(TEXT("/Game/Input/IMC_Default.IMC_Default")); + if (DefaultMCFinder.Succeeded()) + { + DefaultMappingContext = DefaultMCFinder.Object; + } +} + +void ATrivialKartPlayerController::BeginPlay() +{ + Super::BeginPlay(); + + if (!IsLocalPlayerController()) + { + return; + } + + RemapAllDevicesToPrimaryUser(); + + bWasGamepadAttached = QueryAnyGamepadAttached(); + if (bWasGamepadAttached) + { + SetActiveInputMode(ETrivialKartInputMode::Gamepad); + } + + DeviceConnectionChangeHandle = IPlatformInputDeviceMapper::Get().GetOnInputDeviceConnectionChange().AddUObject( + this, &ATrivialKartPlayerController::OnInputDeviceConnectionChange); + + PeriodicDevicePollHandle = FTSTicker::GetCoreTicker().AddTicker( + FTickerDelegate::CreateUObject(this, &ATrivialKartPlayerController::PollDeviceConnectionState), + 0.75f); + + if (FSlateApplication::IsInitialized()) + { + GamepadInputProcessor = MakeShared(this); + FSlateApplication::Get().RegisterInputPreProcessor(GamepadInputProcessor, 0); + } +} + +void ATrivialKartPlayerController::EndPlay(const EEndPlayReason::Type EndPlayReason) +{ + if (PeriodicDevicePollHandle.IsValid()) + { + FTSTicker::GetCoreTicker().RemoveTicker(PeriodicDevicePollHandle); + PeriodicDevicePollHandle.Reset(); + } + if (DeviceCheckTickerHandle.IsValid()) + { + FTSTicker::GetCoreTicker().RemoveTicker(DeviceCheckTickerHandle); + DeviceCheckTickerHandle.Reset(); + } + if (DeviceConnectionChangeHandle.IsValid()) + { + IPlatformInputDeviceMapper::Get().GetOnInputDeviceConnectionChange().Remove(DeviceConnectionChangeHandle); + DeviceConnectionChangeHandle.Reset(); + } + if (GamepadInputProcessor.IsValid() && FSlateApplication::IsInitialized()) + { + FSlateApplication::Get().UnregisterInputPreProcessor(GamepadInputProcessor); + } + GamepadInputProcessor.Reset(); + Super::EndPlay(EndPlayReason); +} + +UInputMappingContext* ATrivialKartPlayerController::GetOrCreateGameplayMappingContext() +{ + if (RuntimeGameplayMappingContext) + { + return RuntimeGameplayMappingContext; + } + if (!DefaultMappingContext) + { + return nullptr; + } + + RuntimeGameplayMappingContext = DuplicateObject(DefaultMappingContext, this); + if (!RuntimeGameplayMappingContext) + { + return DefaultMappingContext; + } + + const UInputAction* MoveAction = nullptr; + for (const FEnhancedActionKeyMapping& Existing : RuntimeGameplayMappingContext->GetMappings()) + { + if (Existing.Action) + { + MoveAction = Existing.Action; + break; + } + } + + if (!MoveAction) + { + return RuntimeGameplayMappingContext; + } + + auto HasKeyMapped = [this, MoveAction](const FKey& Key) -> bool + { + for (const FEnhancedActionKeyMapping& Mapping : RuntimeGameplayMappingContext->GetMappings()) + { + if (Mapping.Action == MoveAction && Mapping.Key == Key) + { + return true; + } + } + return false; + }; + + const FKey StandardDriveKeys[] = { + EKeys::Gamepad_FaceButton_Bottom, + EKeys::Gamepad_DPad_Right, + EKeys::Gamepad_LeftStick_Right, + EKeys::SpaceBar, + EKeys::Right, + EKeys::LeftMouseButton, + EKeys::TouchKeys[0] + }; + + for (const FKey& Key : StandardDriveKeys) + { + if (Key.IsValid() && !HasKeyMapped(Key)) + { + RuntimeGameplayMappingContext->MapKey(MoveAction, Key); + } + } + + UTrivialKartPositiveTriggerModifier* TriggerModifier = + NewObject(RuntimeGameplayMappingContext); + + const FKey TriggerAxisKeys[] = { + EKeys::Gamepad_LeftTriggerAxis, + EKeys::Gamepad_RightTriggerAxis + }; + + for (const FKey& AxisKey : TriggerAxisKeys) + { + if (AxisKey.IsValid() && !HasKeyMapped(AxisKey)) + { + FEnhancedActionKeyMapping& TriggerMapping = RuntimeGameplayMappingContext->MapKey(MoveAction, AxisKey); + if (TriggerModifier) + { + TriggerMapping.Modifiers.Add(TriggerModifier); + } + } + } + + return RuntimeGameplayMappingContext; } void ATrivialKartPlayerController::SetupInputComponent() { Super::SetupInputComponent(); - if (IsLocalPlayerController()) + + if (IsLocalPlayerController() && bGameplayInputEnabled) + { + if (UInputMappingContext* GameplayMC = GetOrCreateGameplayMappingContext()) + { + if (UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem(GetLocalPlayer())) + { + Subsystem->AddMappingContext(GameplayMC, 0); + } + } + } +} + +FKey ATrivialKartPlayerController::ResolveCanonicalUIKey( + const UInputAction* Action, + const TArray& UIMappings) +{ + if (!Action) + { + return EKeys::Invalid; + } + + const FName ActionName = Action->GetFName(); + if (ActionName == TEXT("IA_UI_MoveUp")) + { + return EKeys::Gamepad_DPad_Up; + } + if (ActionName == TEXT("IA_UI_MoveDown")) { - // Add Input Mapping Contexts - if (UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem(GetLocalPlayer())) + return EKeys::Gamepad_DPad_Down; + } + if (ActionName == TEXT("IA_UI_MoveLeft")) + { + return EKeys::Gamepad_DPad_Left; + } + if (ActionName == TEXT("IA_UI_MoveRight")) + { + return EKeys::Gamepad_DPad_Right; + } + if (ActionName == TEXT("IA_UI_Confirm")) + { + return EKeys::Gamepad_FaceButton_Bottom; + } + if (ActionName == TEXT("IA_UI_Cancel")) + { + return EKeys::Gamepad_FaceButton_Right; + } + if (ActionName == TEXT("IA_UI_PrevTab")) + { + return EKeys::Gamepad_LeftShoulder; + } + if (ActionName == TEXT("IA_UI_NextTab")) + { + return EKeys::Gamepad_RightShoulder; + } + + for (const FEnhancedActionKeyMapping& Candidate : UIMappings) + { + if (Candidate.Action == Action && Candidate.Key.IsGamepadKey()) + { + return Candidate.Key; + } + } + return EKeys::Invalid; +} + +FKey ATrivialKartPlayerController::ResolveFallbackUIKey(const FKey& InKey, bool bIsShiftDown) +{ + if (InKey == EKeys::Tab) + { + return bIsShiftDown ? EKeys::Gamepad_LeftShoulder : EKeys::Gamepad_RightShoulder; + } + if (InKey == EKeys::Gamepad_DPad_Up || InKey == EKeys::Up) + { + return EKeys::Gamepad_DPad_Up; + } + if (InKey == EKeys::Gamepad_DPad_Down || InKey == EKeys::Down) + { + return EKeys::Gamepad_DPad_Down; + } + if (InKey == EKeys::Gamepad_DPad_Left || InKey == EKeys::Left) + { + return EKeys::Gamepad_DPad_Left; + } + if (InKey == EKeys::Gamepad_DPad_Right || InKey == EKeys::Right) + { + return EKeys::Gamepad_DPad_Right; + } + if (InKey == EKeys::Gamepad_FaceButton_Bottom || InKey == EKeys::Enter) + { + return EKeys::Gamepad_FaceButton_Bottom; + } + if (InKey == EKeys::Gamepad_FaceButton_Right || InKey == EKeys::Escape || InKey == EKeys::BackSpace) + { + return EKeys::Gamepad_FaceButton_Right; + } + if (InKey == EKeys::Gamepad_LeftShoulder) + { + return EKeys::Gamepad_LeftShoulder; + } + if (InKey == EKeys::Gamepad_RightShoulder) + { + return EKeys::Gamepad_RightShoulder; + } + return EKeys::Invalid; +} + +bool ATrivialKartPlayerController::IsDirectionalUIKey(const FKey& Key) +{ + return Key == EKeys::Gamepad_DPad_Up + || Key == EKeys::Gamepad_DPad_Down + || Key == EKeys::Gamepad_DPad_Left + || Key == EKeys::Gamepad_DPad_Right; +} + +bool ATrivialKartPlayerController::HandleGamepadKey(const FKey& InKey, bool bIsPressed, bool bIsRepeat, bool bIsShiftDown) +{ + ATrivialKartHUD* CurrentHUD = Cast(GetHUD()); + if (!CurrentHUD) + { + return false; + } + + // SpaceBar on PlayBoard always drives the kart as instructed by the HUD banner, even if mouse hovers a bottom menu button + if (!IsSubMenuOpen() && InKey == EKeys::SpaceBar) + { + if (bIsPressed) + { + CurrentHUD->ClearPlayBoardMenuFocus(); + } + return false; + } + + FKey CanonicalKey = EKeys::Invalid; + bool bAllowRepeat = false; + + if (UIMappingContext && InKey != EKeys::Tab) + { + const TArray& UIMappings = UIMappingContext->GetMappings(); + for (const FEnhancedActionKeyMapping& Mapping : UIMappings) + { + if (Mapping.Key == InKey && Mapping.Action) + { + CanonicalKey = ResolveCanonicalUIKey(Mapping.Action, UIMappings); + bAllowRepeat = (Mapping.Action->ValueType != EInputActionValueType::Boolean) || IsDirectionalUIKey(CanonicalKey); + break; + } + } + } + + if (!CanonicalKey.IsValid()) + { + CanonicalKey = ResolveFallbackUIKey(InKey, bIsShiftDown); + bAllowRepeat = IsDirectionalUIKey(CanonicalKey); + } + + if (CanonicalKey.IsValid()) + { + if (bIsPressed && bIsRepeat && !bAllowRepeat) { - Subsystem->AddMappingContext(DefaultMappingContext, 0); + return IsUIBlockingInput(); + } + + if (CurrentHUD->HandleGamepadKey(CanonicalKey, bIsPressed, bIsRepeat)) + { + if (bIsPressed) + { + SetKeyNavigationActive(true); + } + return true; } } + + UInputMappingContext* GameplayMC = GetOrCreateGameplayMappingContext(); + if (bIsPressed && GameplayMC && !IsUIBlockingInput()) + { + for (const FEnhancedActionKeyMapping& Mapping : GameplayMC->GetMappings()) + { + if (Mapping.Key == InKey) + { + CurrentHUD->ClearPlayBoardMenuFocus(); + break; + } + } + } + + return false; +} + +bool ATrivialKartPlayerController::HandleUICancelKey(bool bIsPressed) +{ + if (ATrivialKartHUD* CurrentHUD = Cast(GetHUD())) + { + return CurrentHUD->HandleGamepadKey(EKeys::Gamepad_FaceButton_Right, bIsPressed); + } + return false; +} + +bool ATrivialKartPlayerController::IsSubMenuOpen() const +{ + if (const ATrivialKartHUD* CurrentHUD = Cast(GetHUD())) + { + return CurrentHUD->IsSubMenuOpen(); + } + return false; +} + +bool ATrivialKartPlayerController::IsUIBlockingInput() const +{ + if (const ATrivialKartHUD* CurrentHUD = Cast(GetHUD())) + { + return CurrentHUD->IsUIBlockingInput(); + } + return false; +} + +bool ATrivialKartPlayerController::IsStickNavigationEnabled() const +{ + if (const ATrivialKartHUD* CurrentHUD = Cast(GetHUD())) + { + return CurrentHUD->IsStickNavigationEnabled(); + } + return false; +} + +void ATrivialKartPlayerController::SetGameplayInputEnabled(bool bEnabled) +{ + UInputMappingContext* GameplayMC = GetOrCreateGameplayMappingContext(); + if (bGameplayInputEnabled == bEnabled || !GameplayMC) + { + return; + } + bGameplayInputEnabled = bEnabled; + + if (UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem(GetLocalPlayer())) + { + FModifyContextOptions Options; + Options.bForceImmediately = true; + if (bGameplayInputEnabled) + { + Subsystem->AddMappingContext(GameplayMC, 0, Options); + } + else + { + Subsystem->RemoveMappingContext(GameplayMC, Options); + } + } +} + +void ATrivialKartPlayerController::NotifyExplicitDeviceInput(ETrivialKartInputMode DetectedMode) +{ + if (DetectedMode != ETrivialKartInputMode::Gamepad) + { + LastNonGamepadInputTimeSeconds = FPlatformTime::Seconds(); + } + else + { + bKeyNavigationActive = true; + } + SetActiveInputMode(DetectedMode); +} + +void ATrivialKartPlayerController::NotifyPointerDeviceInput(ETrivialKartInputMode PointerMode) +{ + LastNonGamepadInputTimeSeconds = FPlatformTime::Seconds(); + const bool bWasKeyNav = bKeyNavigationActive; + bKeyNavigationActive = false; + + if (ActiveInputMode != PointerMode) + { + SetActiveInputMode(PointerMode); + } + else if (bWasKeyNav) + { + OnInputModeUpdated.Broadcast(ActiveInputMode); + } +} + +void ATrivialKartPlayerController::SetKeyNavigationActive(bool bActive) +{ + if (bKeyNavigationActive != bActive) + { + bKeyNavigationActive = bActive; + OnInputModeUpdated.Broadcast(ActiveInputMode); + } +} + +void ATrivialKartPlayerController::SetActiveInputMode(ETrivialKartInputMode NewMode) +{ + if (!IsInGameThread()) + { + TWeakObjectPtr WeakThis(this); + AsyncTask(ENamedThreads::GameThread, [WeakThis, NewMode]() + { + if (ATrivialKartPlayerController* StrongThis = WeakThis.Get()) + { + StrongThis->SetActiveInputMode(NewMode); + } + }); + return; + } + + if (ActiveInputMode == NewMode) + { + return; + } + + if (NewMode != ETrivialKartInputMode::Gamepad) + { + PreviousNonGamepadMode = NewMode; + if (GamepadInputProcessor.IsValid()) + { + GamepadInputProcessor->ResetAnalogState(); + } + } + else + { + bKeyNavigationActive = true; + } + + ActiveInputMode = NewMode; + bShowMouseCursor = (ActiveInputMode == ETrivialKartInputMode::KeyboardMouse); + OnInputModeUpdated.Broadcast(ActiveInputMode); +} + +void ATrivialKartPlayerController::ClearPlayBoardMenuFocus() +{ + if (ATrivialKartHUD* CurrentHUD = Cast(GetHUD())) + { + CurrentHUD->ClearPlayBoardMenuFocus(); + } +} + +void ATrivialKartPlayerController::NotifyViewportPointerDown(const FVector2D& ScreenSpacePosition) +{ + if (ATrivialKartHUD* CurrentHUD = Cast(GetHUD())) + { + CurrentHUD->NotifyViewportPointerDown(ScreenSpacePosition); + } +} + +void ATrivialKartPlayerController::CancelPendingPresses() +{ + if (ATrivialKartHUD* CurrentHUD = Cast(GetHUD())) + { + CurrentHUD->CancelPendingPresses(); + } +} + +void ATrivialKartPlayerController::LatchStickUntilNeutral() +{ + if (GamepadInputProcessor.IsValid()) + { + GamepadInputProcessor->LatchStickUntilNeutral(); + } +} + +void ATrivialKartPlayerController::RestoreFocusToGameViewport() +{ + if (!FSlateApplication::IsInitialized()) + { + return; + } + if (const ULocalPlayer* LocalPlayer = GetLocalPlayer()) + { + if (UGameViewportClient* ViewportClient = LocalPlayer->ViewportClient) + { + if (TSharedPtr ViewportWidget = ViewportClient->GetGameViewportWidget()) + { + FSlateApplication::Get().SetUserFocus(GetLocalPlayerUserIndex(), ViewportWidget, EFocusCause::SetDirectly); + } + } + } +} + +int32 ATrivialKartPlayerController::GetLocalPlayerUserIndex() const +{ + if (const ULocalPlayer* LocalPlayer = GetLocalPlayer()) + { + return LocalPlayer->GetControllerId(); + } + return 0; +} + +bool ATrivialKartPlayerController::ShouldAcceptInputFromUser(int32 EventUserIndex, bool bIsGamepadEvent) const +{ + if (EventUserIndex == GetLocalPlayerUserIndex()) + { + return true; + } + if (bIsGamepadEvent) + { + if (const UGameInstance* GI = GetGameInstance()) + { + if (GI->GetNumLocalPlayers() <= 1) + { + return true; + } + } + else + { + return true; + } + } + return false; +} + +bool ATrivialKartPlayerController::IsGameViewportFocused() const +{ + if (!FSlateApplication::IsInitialized()) + { + return false; + } + if (const ULocalPlayer* LocalPlayer = GetLocalPlayer()) + { + if (UGameViewportClient* ViewportClient = LocalPlayer->ViewportClient) + { + if (TSharedPtr ViewportWidget = ViewportClient->GetGameViewportWidget()) + { + return ViewportWidget->HasAnyUserFocusOrFocusedDescendants(); + } + } + } + return false; +} + +bool ATrivialKartPlayerController::IsScreenPositionInGameViewport(const FVector2D& ScreenSpacePosition) const +{ + if (const ULocalPlayer* LocalPlayer = GetLocalPlayer()) + { + if (UGameViewportClient* ViewportClient = LocalPlayer->ViewportClient) + { + if (TSharedPtr ViewportWidget = ViewportClient->GetGameViewportWidget()) + { + return ViewportWidget->GetTickSpaceGeometry().IsUnderLocation(ScreenSpacePosition); + } + } + } + return false; +} + +bool ATrivialKartPlayerController::QueryAnyGamepadAttached() +{ + if (!FSlateApplication::IsInitialized()) + { + return false; + } + const TSharedPtr PlatformApp = FSlateApplication::Get().GetPlatformApplication(); + return PlatformApp.IsValid() && PlatformApp->IsGamepadAttached(); +} + +void ATrivialKartPlayerController::RemapAllDevicesToPrimaryUser() const +{ +#if !WITH_EDITOR + if (const UGameInstance* GI = GetGameInstance()) + { + if (GI->GetNumLocalPlayers() > 1) + { + return; + } + } + + IPlatformInputDeviceMapper& Mapper = IPlatformInputDeviceMapper::Get(); + const FPlatformUserId PrimaryUser = Mapper.GetPrimaryPlatformUser(); + if (!PrimaryUser.IsValid()) + { + return; + } + + TArray ActiveUsers; + Mapper.GetAllActiveUsers(ActiveUsers); + for (const FPlatformUserId& UserId : ActiveUsers) + { + if (UserId.IsValid() && UserId != PrimaryUser) + { + TArray UserDevices; + Mapper.GetAllConnectedInputDevicesForUser(UserId, UserDevices); + for (const FInputDeviceId& DeviceId : UserDevices) + { + if (DeviceId.IsValid()) + { + Mapper.Internal_ChangeInputDeviceUserMapping(DeviceId, PrimaryUser, UserId); + } + } + } + } +#endif +} + +void ATrivialKartPlayerController::SyncGamepadAttachmentState() +{ + RemapAllDevicesToPrimaryUser(); + + const bool bNowAttached = QueryAnyGamepadAttached(); + const bool bJustAttachedFirstGamepad = (!bWasGamepadAttached && bNowAttached); + bWasGamepadAttached = bNowAttached; + + if (bJustAttachedFirstGamepad) + { + if ((FPlatformTime::Seconds() - LastNonGamepadInputTimeSeconds) > 0.25) + { + SetActiveInputMode(ETrivialKartInputMode::Gamepad); + } + } + else if (!bNowAttached && ActiveInputMode == ETrivialKartInputMode::Gamepad) + { + if (GamepadInputProcessor.IsValid()) + { + GamepadInputProcessor->ResetState(); + } +#if PLATFORM_ANDROID + SetActiveInputMode(ETrivialKartInputMode::Touch); +#else + SetActiveInputMode(PreviousNonGamepadMode); +#endif + } +} + +void ATrivialKartPlayerController::OnInputDeviceConnectionChange( + EInputDeviceConnectionState NewConnectionState, + FPlatformUserId PlatformUserId, + FInputDeviceId InputDeviceId) +{ + if (!IsInGameThread()) + { + TWeakObjectPtr WeakThis(this); + AsyncTask(ENamedThreads::GameThread, [WeakThis, NewConnectionState, PlatformUserId, InputDeviceId]() + { + if (ATrivialKartPlayerController* StrongThis = WeakThis.Get()) + { + StrongThis->OnInputDeviceConnectionChange(NewConnectionState, PlatformUserId, InputDeviceId); + } + }); + return; + } + + RemapAllDevicesToPrimaryUser(); + + if (!DeviceCheckTickerHandle.IsValid()) + { + DeviceCheckTickerHandle = FTSTicker::GetCoreTicker().AddTicker( + FTickerDelegate::CreateUObject(this, &ATrivialKartPlayerController::EvaluateDeferredDeviceConnectionState), + 0.0f); + } +} + +bool ATrivialKartPlayerController::EvaluateDeferredDeviceConnectionState(float DeltaTime) +{ + DeviceCheckTickerHandle.Reset(); + SyncGamepadAttachmentState(); + return false; +} + +bool ATrivialKartPlayerController::PollDeviceConnectionState(float DeltaTime) +{ + SyncGamepadAttachmentState(); + return true; } diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/GarageWidget.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/GarageWidget.cpp index 39bf3210..cee0e8e1 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/GarageWidget.cpp +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/GarageWidget.cpp @@ -18,35 +18,179 @@ #include "Widgets/GarageWidget.h" #include "Actors/TrivialKartHUD.h" +#include "Blueprint/WidgetTree.h" +#include "Components/Border.h" #include "Components/Button.h" #include "Components/CheckBox.h" +#include "Components/HorizontalBox.h" +#include "Components/Image.h" +#include "Components/Overlay.h" +#include "Components/OverlaySlot.h" +#include "Components/PanelWidget.h" +#include "Components/ScrollBox.h" +#include "Components/TextBlock.h" +#include "Components/VerticalBox.h" #include "Components/WidgetSwitcher.h" +#include "GameInstances/TrivialKartGameInstance.h" +#include "Objects/TrivialKartSaveGame.h" +#include "Widgets/SelectableItem.h" + +static UBorder* EnsureGarageTabHighlightBorder(UWidgetTree* WidgetTree, UCheckBox* CB) +{ + UOverlay* ParentOverlay = CB ? Cast(CB->GetParent()) : nullptr; + if (!WidgetTree || !ParentOverlay) + { + return nullptr; + } + + UBorder* Border = WidgetTree->ConstructWidget(UBorder::StaticClass()); + Border->SetVisibility(ESlateVisibility::Collapsed); + Border->SetPadding(FMargin(0.0f)); + if (UOverlaySlot* OverlaySlot = ParentOverlay->AddChildToOverlay(Border)) + { + OverlaySlot->SetHorizontalAlignment(HAlign_Fill); + OverlaySlot->SetVerticalAlignment(VAlign_Fill); + } + return Border; +} void UGarageWidget::NativeConstruct() { Super::NativeConstruct(); + + // Keep the modal root hit-testable so empty modal space blocks clicks from piercing into FSceneViewport + SetVisibility(ESlateVisibility::Visible); + + if (WidgetTree) + { + UWidget* TreeRoot = WidgetTree->RootWidget; + WidgetTree->ForEachWidget([TreeRoot](UWidget* Widget) + { + if (!Widget || Widget == TreeRoot || Widget->GetVisibility() != ESlateVisibility::Visible) + { + return; + } + if (Cast(Widget) || Cast(Widget)) + { + Widget->SetVisibility(ESlateVisibility::HitTestInvisible); + } + else if (Cast(Widget) || Cast(Widget) || Cast(Widget)) + { + Widget->SetVisibility(ESlateVisibility::SelfHitTestInvisible); + } + }); + } - BackButton->OnClicked.AddUniqueDynamic(this, &UGarageWidget::OnBackButtonClicked); + if (BackButton) + { + if (!bBackStyleCached) + { + OriginalBackButtonStyle = BackButton->GetStyle(); + OriginalBackButtonBgColor = BackButton->GetBackgroundColor(); + bBackStyleCached = true; + } + BackButton->OnClicked.AddUniqueDynamic(this, &UGarageWidget::OnBackButtonClicked); + BackButton->OnReleased.AddUniqueDynamic(this, &UGarageWidget::OnBackButtonReleased); + } + CheckBoxes.Empty(); CheckBoxes.Add(KartCheckBox); CheckBoxes.Add(LevelCheckBox); - KartCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UGarageWidget::OnKartBoxStateChanged); - LevelCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UGarageWidget::OnLevelBoxStateChange); + + if (TabHighlightBorders.Num() != CheckBoxes.Num()) + { + TabHighlightBorders.Empty(); + for (UCheckBox* CB : CheckBoxes) + { + TabHighlightBorders.Add(EnsureGarageTabHighlightBorder(WidgetTree, CB)); + } + } + + if (KartCheckBox) + { + KartCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UGarageWidget::OnKartBoxStateChanged); + } + if (LevelCheckBox) + { + LevelCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UGarageWidget::OnLevelBoxStateChange); + } + + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->OnInputModeUpdated.RemoveAll(this); + PC->OnInputModeUpdated.AddUObject(this, &UGarageWidget::OnInputModeChanged); + } + + GamepadPressedItem.Reset(); + HoveredItem.Reset(); + bBackButtonPressed = false; + RefreshAllItemsOwnership(); + ActiveTabIndex = ContentSwitcher ? ContentSwitcher->GetActiveWidgetIndex() : 0; + FocusedItemIndex = (ActiveTabIndex == 0) ? FindActiveCarItemIndex() : 0; + RefreshGamepadFocus(IsNavigationVisualActive()); } void UGarageWidget::NativeDestruct() { - BackButton->OnClicked.RemoveDynamic(this, &UGarageWidget::OnBackButtonClicked); - KartCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UGarageWidget::OnKartBoxStateChanged); - LevelCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UGarageWidget::OnLevelBoxStateChange); + if (BackButton) + { + BackButton->OnClicked.RemoveDynamic(this, &UGarageWidget::OnBackButtonClicked); + BackButton->OnReleased.RemoveDynamic(this, &UGarageWidget::OnBackButtonReleased); + } + if (KartCheckBox) + { + KartCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UGarageWidget::OnKartBoxStateChanged); + } + if (LevelCheckBox) + { + LevelCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UGarageWidget::OnLevelBoxStateChange); + } + + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->OnInputModeUpdated.RemoveAll(this); + } + + CheckBoxes.Empty(); Super::NativeDestruct(); } +bool UGarageWidget::IsNavigationVisualActive() const +{ + if (const ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + return PC->IsKeyNavigationActive(); + } + return false; +} + +void UGarageWidget::RestoreViewportFocus() const +{ + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->RestoreFocusToGameViewport(); + } +} + +void UGarageWidget::OnInputModeChanged(ETrivialKartInputMode NewInputMode) +{ + if (!IsNavigationVisualActive()) + { + CancelPendingPress(); + } + RefreshGamepadFocus(false); +} + +void UGarageWidget::OnBackButtonReleased() +{ + RestoreViewportFocus(); +} + void UGarageWidget::OnBackButtonClicked() { - if (TWeakObjectPtr PlayerController = GetOwningPlayer(); PlayerController.IsValid()) + if (TWeakObjectPtr PlayerController = GetOwningPlayer(); PlayerController.IsValid()) { - if (const TWeakObjectPtr CurrentHUD = Cast(PlayerController->GetHUD()); + if (const TWeakObjectPtr CurrentHUD = Cast(PlayerController->GetHUD()); CurrentHUD.IsValid()) { CurrentHUD->AddWidgetToScreen(EWidgetType::PlayBoard); @@ -58,13 +202,22 @@ void UGarageWidget::OnBackButtonClicked() void UGarageWidget::SetCheckBoxState(bool bIsChecked, UCheckBox* CheckBox, int ActiveWidgetIndex) { if (CheckBox == nullptr) + { return; + } + CancelPendingPress(); + HoveredItem.Reset(); + FocusedItemIndex = -1; if (bIsChecked) { - ContentSwitcher->SetActiveWidgetIndex(ActiveWidgetIndex); + ActiveTabIndex = ActiveWidgetIndex; + if (ContentSwitcher) + { + ContentSwitcher->SetActiveWidgetIndex(ActiveWidgetIndex); + } for (auto CurrentCheckBox : CheckBoxes) { - if (CurrentCheckBox != CheckBox) + if (CurrentCheckBox && CurrentCheckBox != CheckBox) { CurrentCheckBox->SetCheckedState(ECheckBoxState::Unchecked); } @@ -74,6 +227,469 @@ void UGarageWidget::SetCheckBoxState(bool bIsChecked, UCheckBox* CheckBox, int A { CheckBox->SetCheckedState(ECheckBoxState::Checked); } + RefreshAllItemsOwnership(); + RefreshGamepadFocus(false); + RestoreViewportFocus(); +} + +void UGarageWidget::SelectTabByIndex(int32 NewTabIndex) +{ + if (CheckBoxes.Num() == 0) + { + return; + } + ActiveTabIndex = (NewTabIndex + CheckBoxes.Num()) % CheckBoxes.Num(); + if (UCheckBox* TargetCheckBox = CheckBoxes[ActiveTabIndex]) + { + TargetCheckBox->SetCheckedState(ECheckBoxState::Checked); + SetCheckBoxState(true, TargetCheckBox, ActiveTabIndex); + } +} + +void UGarageWidget::RefreshAllItemsOwnership() const +{ + TArray AllItems; + GatherSelectableItems(ContentSwitcher, AllItems, false); + for (USelectableItem* Item : AllItems) + { + if (Item) + { + Item->RefreshOwnershipState(); + } + } +} + +void UGarageWidget::GatherSelectableItems(UWidget* RootWidget, TArray& OutItems, bool bOnlySelectable) const +{ + if (!RootWidget) + { + return; + } + if (USelectableItem* Item = Cast(RootWidget)) + { + if (!bOnlySelectable || Item->IsItemSelectable()) + { + OutItems.Add(Item); + } + return; + } + if (bOnlySelectable && !RootWidget->IsVisible()) + { + return; + } + if (UPanelWidget* Panel = Cast(RootWidget)) + { + for (int32 i = 0; i < Panel->GetChildrenCount(); ++i) + { + GatherSelectableItems(Panel->GetChildAt(i), OutItems, bOnlySelectable); + } + } +} + +int32 UGarageWidget::FindActiveCarItemIndex() const +{ + if (!ContentSwitcher) + { + return 0; + } + TArray ActiveItems; + GatherSelectableItems(ContentSwitcher->GetActiveWidget(), ActiveItems, true); + if (UTrivialKartGameInstance* Instance = Cast(GetGameInstance())) + { + if (UTrivialKartSaveGame* Save = Instance->LoadGame()) + { + if (!Save->ActiveCarType.IsEmpty()) + { + for (int32 i = 0; i < ActiveItems.Num(); ++i) + { + if (ActiveItems[i] && ActiveItems[i]->GetCarType().Equals(Save->ActiveCarType, ESearchCase::IgnoreCase)) + { + return i; + } + } + } + } + } + return 0; +} + +void UGarageWidget::OnSelectableItemInteracted(USelectableItem* InteractedItem) +{ + HoveredItem = InteractedItem; + TArray ActiveItems; + if (ContentSwitcher) + { + GatherSelectableItems(ContentSwitcher->GetActiveWidget(), ActiveItems, true); + } + const int32 FoundIndex = ActiveItems.IndexOfByKey(InteractedItem); + if (FoundIndex != INDEX_NONE) + { + FocusedItemIndex = FoundIndex; + } + RefreshGamepadFocus(false); +} + +void UGarageWidget::OnSelectableItemUnhovered(USelectableItem* UnhoveredItem) +{ + if (HoveredItem.Get() == UnhoveredItem) + { + HoveredItem.Reset(); + if (!IsNavigationVisualActive()) + { + RefreshGamepadFocus(false); + } + } +} + +void UGarageWidget::OnSelectableItemClicked(USelectableItem* ClickedItem) +{ + RefreshAllItemsOwnership(); + if (ClickedItem && !ClickedItem->IsItemSelectable()) + { + HoveredItem.Reset(); + RefreshGamepadFocus(false); + } + else + { + OnSelectableItemInteracted(ClickedItem); + } +} + +void UGarageWidget::RefreshOwnershipAndFocus(bool bScrollIntoView) +{ + RefreshAllItemsOwnership(); + RefreshGamepadFocus(bScrollIntoView); +} + +void UGarageWidget::CancelPendingPress() +{ + if (USelectableItem* PressedItem = GamepadPressedItem.Get()) + { + PressedItem->SetButtonPressed(false); + } + GamepadPressedItem.Reset(); + if (bBackButtonPressed) + { + bBackButtonPressed = false; + RefreshGamepadFocus(false); + } +} + +void UGarageWidget::RefreshGamepadFocus(bool bScrollIntoView) +{ + const ATrivialKartPlayerController* PC = Cast(GetOwningPlayer()); + const bool bShowNavVisual = IsNavigationVisualActive(); + const bool bAllowMouseHoverVisual = (!bShowNavVisual && PC && PC->GetActiveInputMode() == ETrivialKartInputMode::KeyboardMouse); + + TArray ActiveItems; + if (ContentSwitcher) + { + GatherSelectableItems(ContentSwitcher->GetActiveWidget(), ActiveItems, true); + } + + USelectableItem* FocusedItem = nullptr; + if (ActiveItems.Num() == 0 && FocusedItemIndex >= 0) + { + FocusedItemIndex = -1; + } + else if (FocusedItemIndex >= 0) + { + FocusedItemIndex = FMath::Clamp(FocusedItemIndex, 0, ActiveItems.Num() - 1); + FocusedItem = ActiveItems[FocusedItemIndex]; + } + + TArray AllItems; + GatherSelectableItems(ContentSwitcher, AllItems, false); + for (USelectableItem* Item : AllItems) + { + if (Item) + { + const bool bIsInActiveTab = ActiveItems.Contains(Item); + Item->OnItemInteracted.BindUObject(this, &UGarageWidget::OnSelectableItemInteracted); + Item->OnItemUnhovered.BindUObject(this, &UGarageWidget::OnSelectableItemUnhovered); + Item->OnItemClicked.BindUObject(this, &UGarageWidget::OnSelectableItemClicked); + if (!bIsInActiveTab || (Item != GamepadPressedItem.Get() && !Item->IsButtonHovered())) + { + Item->SetButtonPressed(false); + } + const bool bIsHoveredByMouse = (bAllowMouseHoverVisual && bIsInActiveTab && HoveredItem.Get() == Item && Item->IsButtonHovered()); + const bool bIsFocusedTarget = bShowNavVisual ? (Item == FocusedItem) : bIsHoveredByMouse; + Item->SetGamepadFocused(bIsFocusedTarget, bShowNavVisual || bIsHoveredByMouse); + } + } + + if (FocusedItem && bScrollIntoView && bShowNavVisual) + { + for (UPanelWidget* Parent = FocusedItem->GetParent(); Parent != nullptr; Parent = Parent->GetParent()) + { + if (UScrollBox* ScrollBox = Cast(Parent)) + { + ScrollBox->ScrollWidgetIntoView(FocusedItem, true, EDescendantScrollDestination::IntoView); + break; + } + } + } + + if (BackButton && bBackStyleCached) + { + const bool bBackFocused = bShowNavVisual && (FocusedItemIndex == -2); + BackButton->SetRenderTransformPivot(FVector2D(0.5f, 0.5f)); + if (bBackFocused) + { + const bool bPressed = bBackButtonPressed || BackButton->IsPressed(); + FSlateBrush HighlightBrush; + HighlightBrush.DrawAs = ESlateBrushDrawType::RoundedBox; + HighlightBrush.TintColor = FSlateColor(bPressed + ? FLinearColor(1.0f, 0.35f, 0.0f, 0.68f) + : FLinearColor(1.0f, 0.45f, 0.0f, 0.48f)); + HighlightBrush.OutlineSettings.CornerRadii = FVector4(10.0f, 10.0f, 10.0f, 10.0f); + HighlightBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; + HighlightBrush.OutlineSettings.Color = FSlateColor(FLinearColor(1.0f, 0.9f, 0.0f, 1.0f)); + HighlightBrush.OutlineSettings.Width = 6.0f; + + FButtonStyle FocusedStyle = OriginalBackButtonStyle; + FocusedStyle.SetNormal(HighlightBrush); + FocusedStyle.SetHovered(HighlightBrush); + FocusedStyle.SetPressed(HighlightBrush); + BackButton->SetStyle(FocusedStyle); + BackButton->SetBackgroundColor(FLinearColor::White); + BackButton->SetRenderScale(FVector2D(bPressed ? 0.88f : 1.12f, bPressed ? 0.88f : 1.12f)); + } + else + { + BackButton->SetStyle(OriginalBackButtonStyle); + BackButton->SetBackgroundColor(OriginalBackButtonBgColor); + BackButton->SetRenderScale(FVector2D(1.0f, 1.0f)); + } + } + + const bool bTabBarFocused = bShowNavVisual && (FocusedItemIndex == -1); + for (int32 i = 0; i < CheckBoxes.Num(); ++i) + { + UCheckBox* CB = CheckBoxes[i]; + UBorder* HighlightBorder = TabHighlightBorders.IsValidIndex(i) ? TabHighlightBorders[i].Get() : nullptr; + if (!CB) + { + continue; + } + UWidget* TabScaleTarget = CB->GetParent() + ? static_cast(CB->GetParent()) + : static_cast(CB); + TabScaleTarget->SetRenderTransformPivot(FVector2D(0.5f, 0.5f)); + if (i == ActiveTabIndex) + { + if (HighlightBorder) + { + FSlateBrush OverlayBrush; + OverlayBrush.DrawAs = ESlateBrushDrawType::RoundedBox; + OverlayBrush.ImageSize = CB->GetWidgetStyle().CheckedImage.ImageSize; + OverlayBrush.TintColor = FSlateColor(FLinearColor(1.0f, 0.45f, 0.0f, 0.48f)); + OverlayBrush.OutlineSettings.CornerRadii = FVector4(8.0f, 8.0f, 8.0f, 8.0f); + OverlayBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; + OverlayBrush.OutlineSettings.Color = FSlateColor(bTabBarFocused + ? FLinearColor(1.0f, 0.9f, 0.0f, 1.0f) + : FLinearColor::Transparent); + OverlayBrush.OutlineSettings.Width = bTabBarFocused ? 6.0f : 0.0f; + HighlightBorder->SetBrush(OverlayBrush); + HighlightBorder->SetBrushColor(FLinearColor::White); + HighlightBorder->SetVisibility(ESlateVisibility::HitTestInvisible); + } + const float TargetTabScale = bTabBarFocused ? 1.15f : 1.0f; + TabScaleTarget->SetRenderScale(FVector2D(TargetTabScale, TargetTabScale)); + } + else + { + if (HighlightBorder) + { + HighlightBorder->SetVisibility(ESlateVisibility::Collapsed); + } + TabScaleTarget->SetRenderScale(FVector2D(1.0f, 1.0f)); + } + } +} + +bool UGarageWidget::HandleGamepadKey(const FKey& Key, bool bIsPressed) +{ + if (!bIsPressed) + { + if (Key == EKeys::Gamepad_FaceButton_Bottom) + { + if (bBackButtonPressed) + { + bBackButtonPressed = false; + RefreshGamepadFocus(false); + if (FocusedItemIndex == -2) + { + OnBackButtonClicked(); + } + return true; + } + + USelectableItem* PreviouslyPressed = GamepadPressedItem.Get(); + GamepadPressedItem.Reset(); + + TArray ActiveItems; + if (ContentSwitcher) + { + GatherSelectableItems(ContentSwitcher->GetActiveWidget(), ActiveItems, true); + } + if (PreviouslyPressed && FocusedItemIndex >= 0 && FocusedItemIndex < ActiveItems.Num() && + ActiveItems[FocusedItemIndex] == PreviouslyPressed) + { + PreviouslyPressed->SetButtonPressed(false); + PreviouslyPressed->OnSelectionButtonClicked(); + } + else if (PreviouslyPressed) + { + PreviouslyPressed->SetButtonPressed(false); + } + return true; + } + return false; + } + + if (Key == EKeys::Gamepad_FaceButton_Right) + { + CancelPendingPress(); + OnBackButtonClicked(); + return true; + } + if (Key == EKeys::Gamepad_LeftShoulder) + { + SelectTabByIndex(ActiveTabIndex - 1); + return true; + } + if (Key == EKeys::Gamepad_RightShoulder) + { + SelectTabByIndex(ActiveTabIndex + 1); + return true; + } + + TArray ActiveItems; + if (ContentSwitcher) + { + GatherSelectableItems(ContentSwitcher->GetActiveWidget(), ActiveItems, true); + } + + // If opened via touch/mouse with navigation focus hidden, reveal focus on the first navigation/confirm press + if (!IsNavigationVisualActive()) + { + if (Key == EKeys::Gamepad_DPad_Left || Key == EKeys::Gamepad_DPad_Right || + Key == EKeys::Gamepad_DPad_Up || Key == EKeys::Gamepad_DPad_Down || + Key == EKeys::Gamepad_FaceButton_Bottom) + { + CancelPendingPress(); + if (Key == EKeys::Gamepad_DPad_Up || ActiveItems.Num() == 0) + { + FocusedItemIndex = -1; + } + else if (FocusedItemIndex < 0) + { + FocusedItemIndex = (ActiveTabIndex == 0) ? FindActiveCarItemIndex() : 0; + } + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->SetKeyNavigationActive(true); + } + RefreshGamepadFocus(true); + return true; + } + } + + if (Key == EKeys::Gamepad_DPad_Left) + { + CancelPendingPress(); + if (FocusedItemIndex == -2) + { + RefreshGamepadFocus(false); + } + else if (FocusedItemIndex == -1) + { + SelectTabByIndex(ActiveTabIndex - 1); + } + else if (ActiveItems.Num() > 1) + { + FocusedItemIndex = (FocusedItemIndex + ActiveItems.Num() - 1) % ActiveItems.Num(); + RefreshGamepadFocus(); + } + else + { + RefreshGamepadFocus(); + } + return true; + } + if (Key == EKeys::Gamepad_DPad_Right) + { + CancelPendingPress(); + if (FocusedItemIndex == -2) + { + RefreshGamepadFocus(false); + } + else if (FocusedItemIndex == -1) + { + SelectTabByIndex(ActiveTabIndex + 1); + } + else if (ActiveItems.Num() > 1) + { + FocusedItemIndex = (FocusedItemIndex + 1) % ActiveItems.Num(); + RefreshGamepadFocus(); + } + else + { + RefreshGamepadFocus(); + } + return true; + } + if (Key == EKeys::Gamepad_DPad_Up) + { + CancelPendingPress(); + if (FocusedItemIndex >= 0) + { + FocusedItemIndex = -1; + } + else if (FocusedItemIndex == -1 && BackButton) + { + FocusedItemIndex = -2; + } + RefreshGamepadFocus(false); + return true; + } + if (Key == EKeys::Gamepad_DPad_Down) + { + CancelPendingPress(); + if (FocusedItemIndex == -2) + { + FocusedItemIndex = -1; + } + else if (FocusedItemIndex == -1 && ActiveItems.Num() > 0) + { + FocusedItemIndex = (ActiveTabIndex == 0) ? FindActiveCarItemIndex() : 0; + } + RefreshGamepadFocus(); + return true; + } + if (Key == EKeys::Gamepad_FaceButton_Bottom) + { + if (FocusedItemIndex == -2 && BackButton) + { + bBackButtonPressed = true; + RefreshGamepadFocus(false); + } + else if (FocusedItemIndex >= 0 && FocusedItemIndex < ActiveItems.Num()) + { + GamepadPressedItem = ActiveItems[FocusedItemIndex]; + GamepadPressedItem->SetButtonPressed(true); + } + else if (FocusedItemIndex == -1 && ActiveItems.Num() > 0) + { + GamepadPressedItem.Reset(); + FocusedItemIndex = (ActiveTabIndex == 0) ? FindActiveCarItemIndex() : 0; + RefreshGamepadFocus(); + } + return true; + } + + return false; } void UGarageWidget::OnKartBoxStateChanged(bool bIsChecked) diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/PGSWidget.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/PGSWidget.cpp index ea35e032..a6713611 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/PGSWidget.cpp +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/PGSWidget.cpp @@ -19,28 +19,115 @@ #include "OnlineSubsystem.h" #include "OnlineSubsystemUtils.h" #include "Actors/TrivialKartHUD.h" +#include "Blueprint/WidgetTree.h" +#include "Components/Border.h" #include "Components/Button.h" #include "Components/CheckBox.h" +#include "Components/HorizontalBox.h" +#include "Components/Image.h" +#include "Components/Overlay.h" +#include "Components/OverlaySlot.h" #include "Components/ScrollBox.h" +#include "Components/TextBlock.h" #include "Components/VerticalBox.h" #include "Components/WidgetSwitcher.h" #include "GameInstances/TrivialKartGameInstance.h" #include "Interfaces/OnlineAchievementsInterface.h" #include "Widgets/PGSLayoutText.h" +static UBorder* EnsurePGSTabHighlightBorder(UWidgetTree* WidgetTree, UCheckBox* CB) +{ + UOverlay* ParentOverlay = CB ? Cast(CB->GetParent()) : nullptr; + if (!WidgetTree || !ParentOverlay) + { + return nullptr; + } + + UBorder* Border = WidgetTree->ConstructWidget(UBorder::StaticClass()); + Border->SetVisibility(ESlateVisibility::Collapsed); + Border->SetPadding(FMargin(0.0f)); + if (UOverlaySlot* OverlaySlot = ParentOverlay->AddChildToOverlay(Border)) + { + OverlaySlot->SetHorizontalAlignment(HAlign_Fill); + OverlaySlot->SetVerticalAlignment(VAlign_Fill); + } + return Border; +} + void UPGSWidget::NativeConstruct() { Super::NativeConstruct(); - BackButton->OnClicked.AddUniqueDynamic(this, &UPGSWidget::OnBackButtonClicked); + + // Keep the modal root hit-testable so empty modal space blocks clicks from piercing into FSceneViewport + SetVisibility(ESlateVisibility::Visible); + + if (WidgetTree) + { + UWidget* TreeRoot = WidgetTree->RootWidget; + WidgetTree->ForEachWidget([TreeRoot](UWidget* Widget) + { + if (!Widget || Widget == TreeRoot || Widget->GetVisibility() != ESlateVisibility::Visible) + { + return; + } + if (Cast(Widget) || Cast(Widget)) + { + Widget->SetVisibility(ESlateVisibility::HitTestInvisible); + } + else if (Cast(Widget) || Cast(Widget) || Cast(Widget)) + { + Widget->SetVisibility(ESlateVisibility::SelfHitTestInvisible); + } + }); + } + + if (BackButton) + { + if (!bBackStyleCached) + { + OriginalBackButtonStyle = BackButton->GetStyle(); + OriginalBackButtonBgColor = BackButton->GetBackgroundColor(); + bBackStyleCached = true; + } + BackButton->OnClicked.AddUniqueDynamic(this, &UPGSWidget::OnBackButtonClicked); + BackButton->OnReleased.AddUniqueDynamic(this, &UPGSWidget::OnBackButtonReleased); + } + CheckBoxes.Empty(); CheckBoxes.Add(AuthenticationCheckBox); CheckBoxes.Add(AchievementsCheckBox); CheckBoxes.Add(LeaderboardCheckBox); - AuthenticationCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UPGSWidget::OnAuthCheckBoxStateChanged); - AchievementsCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UPGSWidget::OnAchievementBoxStateChange); - LeaderboardCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UPGSWidget::OnLeaderboardBoxStateChange); - if (TWeakObjectPtr Instance = Cast(GetGameInstance()); - Instance.IsValid()) + + if (TabHighlightBorders.Num() != CheckBoxes.Num()) + { + TabHighlightBorders.Empty(); + for (UCheckBox* CB : CheckBoxes) + { + TabHighlightBorders.Add(EnsurePGSTabHighlightBorder(WidgetTree, CB)); + } + } + + if (AuthenticationCheckBox) + { + AuthenticationCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UPGSWidget::OnAuthCheckBoxStateChanged); + } + if (AchievementsCheckBox) + { + AchievementsCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UPGSWidget::OnAchievementBoxStateChange); + } + if (LeaderboardCheckBox) + { + LeaderboardCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UPGSWidget::OnLeaderboardBoxStateChange); + } + + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->OnInputModeUpdated.RemoveAll(this); + PC->OnInputModeUpdated.AddUObject(this, &UPGSWidget::OnInputModeChanged); + } + + if (TWeakObjectPtr Instance = Cast(GetGameInstance()); + Instance.IsValid() && AuthBox && PGSTextTemplate) { const FString AuthStatus = Instance->GetLoginStatus() ? FString("Logged In") : FString("Logged Out"); if (const auto PgsAuthStatusText = Cast( @@ -57,44 +144,111 @@ void UPGSWidget::NativeConstruct() } } if (const IOnlineIdentityPtr IdentityInterface = Online::GetIdentityInterface(GetWorld()); - IdentityInterface.IsValid()) + IdentityInterface.IsValid() && AchievementsBox && PGSTextTemplate) { - if (const IOnlineAchievementsPtr AchievementsInterface = - Online::GetAchievementsInterface(GetWorld()); AchievementsInterface.IsValid()) + if (const TSharedPtr UniquePlayerId = IdentityInterface->GetUniquePlayerId(0); UniquePlayerId.IsValid()) { - TArray Achievements; - if (AchievementsInterface->GetCachedAchievements( - *IdentityInterface->GetUniquePlayerId(0), Achievements) - == EOnlineCachedResult::Success) + if (const IOnlineAchievementsPtr AchievementsInterface = + Online::GetAchievementsInterface(GetWorld()); AchievementsInterface.IsValid()) { - for (auto Achievement : Achievements) + TArray Achievements; + if (AchievementsInterface->GetCachedAchievements(*UniquePlayerId, Achievements) + == EOnlineCachedResult::Success) { - if (auto PGSText = Cast( - CreateWidget(this, PGSTextTemplate))) + for (auto Achievement : Achievements) { - PGSText->SetPGSText(Achievement.Id, FString::Printf(TEXT("%.1f"), Achievement.Progress)); - AchievementsBox->AddChild(PGSText); + if (auto PGSText = Cast( + CreateWidget(this, PGSTextTemplate))) + { + PGSText->SetPGSText(Achievement.Id, FString::Printf(TEXT("%.1f"), Achievement.Progress)); + AchievementsBox->AddChild(PGSText); + } } } } } } + + bBackButtonFocused = false; + bBackButtonPressed = false; + ActiveTabIndex = ContentSwitcher ? ContentSwitcher->GetActiveWidgetIndex() : 0; + UpdateTabFocusVisuals(); } void UPGSWidget::NativeDestruct() { - BackButton->OnClicked.RemoveDynamic(this, &UPGSWidget::OnBackButtonClicked); - AuthenticationCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UPGSWidget::OnAuthCheckBoxStateChanged); - AchievementsCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UPGSWidget::OnAchievementBoxStateChange); - LeaderboardCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UPGSWidget::OnLeaderboardBoxStateChange); + if (BackButton) + { + BackButton->OnClicked.RemoveDynamic(this, &UPGSWidget::OnBackButtonClicked); + BackButton->OnReleased.RemoveDynamic(this, &UPGSWidget::OnBackButtonReleased); + } + if (AuthenticationCheckBox) + { + AuthenticationCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UPGSWidget::OnAuthCheckBoxStateChanged); + } + if (AchievementsCheckBox) + { + AchievementsCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UPGSWidget::OnAchievementBoxStateChange); + } + if (LeaderboardCheckBox) + { + LeaderboardCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UPGSWidget::OnLeaderboardBoxStateChange); + } + + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->OnInputModeUpdated.RemoveAll(this); + } + + CheckBoxes.Empty(); Super::NativeDestruct(); } +bool UPGSWidget::IsNavigationVisualActive() const +{ + if (const ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + return PC->IsKeyNavigationActive(); + } + return false; +} + +void UPGSWidget::RestoreViewportFocus() const +{ + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->RestoreFocusToGameViewport(); + } +} + +void UPGSWidget::OnInputModeChanged(ETrivialKartInputMode NewInputMode) +{ + if (!IsNavigationVisualActive()) + { + CancelPendingPress(); + } + UpdateTabFocusVisuals(); +} + +void UPGSWidget::CancelPendingPress() +{ + if (bBackButtonPressed) + { + bBackButtonPressed = false; + UpdateTabFocusVisuals(); + } +} + +void UPGSWidget::OnBackButtonReleased() +{ + RestoreViewportFocus(); +} + void UPGSWidget::OnBackButtonClicked() { - if (TWeakObjectPtr PlayerController = GetOwningPlayer(); PlayerController.IsValid()) + if (TWeakObjectPtr PlayerController = GetOwningPlayer(); PlayerController.IsValid()) { - if (const TWeakObjectPtr CurrentHUD = Cast(PlayerController->GetHUD()); + if (const TWeakObjectPtr CurrentHUD = Cast(PlayerController->GetHUD()); CurrentHUD.IsValid()) { CurrentHUD->AddWidgetToScreen(EWidgetType::PlayBoard); @@ -106,13 +260,21 @@ void UPGSWidget::OnBackButtonClicked() void UPGSWidget::SetCheckBoxState(bool bIsChecked, UCheckBox* CheckBox, int ActiveWidgetIndex) { if (CheckBox == nullptr) + { return; + } + CancelPendingPress(); + bBackButtonFocused = false; if (bIsChecked) { - ContentSwitcher->SetActiveWidgetIndex(ActiveWidgetIndex); + ActiveTabIndex = ActiveWidgetIndex; + if (ContentSwitcher) + { + ContentSwitcher->SetActiveWidgetIndex(ActiveWidgetIndex); + } for (auto CurrentCheckBox : CheckBoxes) { - if (CurrentCheckBox != CheckBox) + if (CurrentCheckBox && CurrentCheckBox != CheckBox) { CurrentCheckBox->SetCheckedState(ECheckBoxState::Unchecked); } @@ -122,6 +284,201 @@ void UPGSWidget::SetCheckBoxState(bool bIsChecked, UCheckBox* CheckBox, int Acti { CheckBox->SetCheckedState(ECheckBoxState::Checked); } + UpdateTabFocusVisuals(); + RestoreViewportFocus(); +} + +void UPGSWidget::SelectTabByIndex(int32 NewTabIndex) +{ + if (CheckBoxes.Num() == 0) + { + return; + } + bBackButtonFocused = false; + ActiveTabIndex = (NewTabIndex + CheckBoxes.Num()) % CheckBoxes.Num(); + if (UCheckBox* TargetCheckBox = CheckBoxes[ActiveTabIndex]) + { + TargetCheckBox->SetCheckedState(ECheckBoxState::Checked); + SetCheckBoxState(true, TargetCheckBox, ActiveTabIndex); + } +} + +void UPGSWidget::UpdateTabFocusVisuals() +{ + const bool bShowNavVisual = IsNavigationVisualActive(); + + if (BackButton && bBackStyleCached) + { + const bool bBackActive = bShowNavVisual && bBackButtonFocused; + BackButton->SetRenderTransformPivot(FVector2D(0.5f, 0.5f)); + if (bBackActive) + { + const bool bPressed = bBackButtonPressed || BackButton->IsPressed(); + FSlateBrush HighlightBrush; + HighlightBrush.DrawAs = ESlateBrushDrawType::RoundedBox; + HighlightBrush.TintColor = FSlateColor(bPressed + ? FLinearColor(1.0f, 0.35f, 0.0f, 0.68f) + : FLinearColor(1.0f, 0.45f, 0.0f, 0.48f)); + HighlightBrush.OutlineSettings.CornerRadii = FVector4(10.0f, 10.0f, 10.0f, 10.0f); + HighlightBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; + HighlightBrush.OutlineSettings.Color = FSlateColor(FLinearColor(1.0f, 0.9f, 0.0f, 1.0f)); + HighlightBrush.OutlineSettings.Width = 6.0f; + + FButtonStyle FocusedStyle = OriginalBackButtonStyle; + FocusedStyle.SetNormal(HighlightBrush); + FocusedStyle.SetHovered(HighlightBrush); + FocusedStyle.SetPressed(HighlightBrush); + BackButton->SetStyle(FocusedStyle); + BackButton->SetBackgroundColor(FLinearColor::White); + BackButton->SetRenderScale(FVector2D(bPressed ? 0.88f : 1.12f, bPressed ? 0.88f : 1.12f)); + } + else + { + BackButton->SetStyle(OriginalBackButtonStyle); + BackButton->SetBackgroundColor(OriginalBackButtonBgColor); + BackButton->SetRenderScale(FVector2D(1.0f, 1.0f)); + } + } + + const bool bTabBarFocused = bShowNavVisual && !bBackButtonFocused; + for (int32 i = 0; i < CheckBoxes.Num(); ++i) + { + UCheckBox* CB = CheckBoxes[i]; + UBorder* HighlightBorder = TabHighlightBorders.IsValidIndex(i) ? TabHighlightBorders[i].Get() : nullptr; + if (!CB) + { + continue; + } + UWidget* TabScaleTarget = CB->GetParent() + ? static_cast(CB->GetParent()) + : static_cast(CB); + TabScaleTarget->SetRenderTransformPivot(FVector2D(0.5f, 0.5f)); + if (i == ActiveTabIndex) + { + if (HighlightBorder) + { + FSlateBrush OverlayBrush; + OverlayBrush.DrawAs = ESlateBrushDrawType::RoundedBox; + OverlayBrush.ImageSize = CB->GetWidgetStyle().CheckedImage.ImageSize; + OverlayBrush.TintColor = FSlateColor(FLinearColor(1.0f, 0.45f, 0.0f, 0.48f)); + OverlayBrush.OutlineSettings.CornerRadii = FVector4(8.0f, 8.0f, 8.0f, 8.0f); + OverlayBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; + OverlayBrush.OutlineSettings.Color = FSlateColor(bTabBarFocused + ? FLinearColor(1.0f, 0.9f, 0.0f, 1.0f) + : FLinearColor::Transparent); + OverlayBrush.OutlineSettings.Width = bTabBarFocused ? 6.0f : 0.0f; + HighlightBorder->SetBrush(OverlayBrush); + HighlightBorder->SetBrushColor(FLinearColor::White); + HighlightBorder->SetVisibility(ESlateVisibility::HitTestInvisible); + } + const float TargetTabScale = bTabBarFocused ? 1.15f : 1.0f; + TabScaleTarget->SetRenderScale(FVector2D(TargetTabScale, TargetTabScale)); + } + else + { + if (HighlightBorder) + { + HighlightBorder->SetVisibility(ESlateVisibility::Collapsed); + } + TabScaleTarget->SetRenderScale(FVector2D(1.0f, 1.0f)); + } + } +} + +bool UPGSWidget::HandleGamepadKey(const FKey& Key, bool bIsPressed) +{ + if (!bIsPressed) + { + if (Key == EKeys::Gamepad_FaceButton_Bottom && bBackButtonPressed) + { + bBackButtonPressed = false; + UpdateTabFocusVisuals(); + if (bBackButtonFocused) + { + OnBackButtonClicked(); + } + return true; + } + return false; + } + + if (Key == EKeys::Gamepad_FaceButton_Right) + { + CancelPendingPress(); + OnBackButtonClicked(); + return true; + } + if (!IsNavigationVisualActive() && + (Key == EKeys::Gamepad_DPad_Left || Key == EKeys::Gamepad_DPad_Right || + Key == EKeys::Gamepad_DPad_Up || Key == EKeys::Gamepad_DPad_Down || + Key == EKeys::Gamepad_FaceButton_Bottom)) + { + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->SetKeyNavigationActive(true); + } + UpdateTabFocusVisuals(); + return true; + } + if (Key == EKeys::Gamepad_FaceButton_Bottom) + { + if (bBackButtonFocused && BackButton) + { + bBackButtonPressed = true; + UpdateTabFocusVisuals(); + } + return true; + } + if (Key == EKeys::Gamepad_LeftShoulder || Key == EKeys::Gamepad_DPad_Left) + { + if (bBackButtonFocused && Key == EKeys::Gamepad_DPad_Left) + { + return true; + } + SelectTabByIndex(ActiveTabIndex - 1); + return true; + } + if (Key == EKeys::Gamepad_RightShoulder || Key == EKeys::Gamepad_DPad_Right) + { + if (bBackButtonFocused && Key == EKeys::Gamepad_DPad_Right) + { + return true; + } + SelectTabByIndex(ActiveTabIndex + 1); + return true; + } + if (Key == EKeys::Gamepad_DPad_Up) + { + UScrollBox* TargetScroll = (ActiveTabIndex == 1) ? AchievementsBox.Get() : ((ActiveTabIndex == 2) ? LeaderboardBox.Get() : nullptr); + if (!bBackButtonFocused && TargetScroll && TargetScroll->GetScrollOffset() > KINDA_SMALL_NUMBER) + { + const float MaxOffset = FMath::Max(0.0f, TargetScroll->GetScrollOffsetOfEnd()); + TargetScroll->SetScrollOffset(FMath::Clamp(TargetScroll->GetScrollOffset() - 60.0f, 0.0f, MaxOffset)); + } + else if (!bBackButtonFocused && BackButton) + { + bBackButtonFocused = true; + UpdateTabFocusVisuals(); + } + return true; + } + if (Key == EKeys::Gamepad_DPad_Down) + { + if (bBackButtonFocused) + { + bBackButtonFocused = false; + UpdateTabFocusVisuals(); + return true; + } + UScrollBox* TargetScroll = (ActiveTabIndex == 1) ? AchievementsBox.Get() : ((ActiveTabIndex == 2) ? LeaderboardBox.Get() : nullptr); + if (TargetScroll) + { + const float MaxOffset = FMath::Max(0.0f, TargetScroll->GetScrollOffsetOfEnd()); + TargetScroll->SetScrollOffset(FMath::Clamp(TargetScroll->GetScrollOffset() + 60.0f, 0.0f, MaxOffset)); + } + return true; + } + return false; } void UPGSWidget::OnAuthCheckBoxStateChanged(bool bIsChecked) diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/PlayBoardWidget.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/PlayBoardWidget.cpp index 38a192b2..22a18e14 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/PlayBoardWidget.cpp +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/PlayBoardWidget.cpp @@ -18,20 +18,347 @@ #include "Widgets/PlayBoardWidget.h" #include "Actors/TrivialKartHUD.h" +#include "Blueprint/WidgetTree.h" +#include "Components/Border.h" #include "Components/Button.h" +#include "Components/HorizontalBox.h" +#include "Components/Image.h" +#include "Components/Overlay.h" +#include "Components/OverlaySlot.h" #include "Components/ProgressBar.h" +#include "Components/SizeBox.h" #include "Components/TextBlock.h" +#include "Components/VerticalBox.h" +#include "Components/VerticalBoxSlot.h" +#include "Engine/Texture2D.h" #include "Infos/TrivialKartPlayerState.h" +TSharedRef UPlayBoardWidget::RebuildWidget() +{ + if (!IsDesignTime()) + { + EnsureInputGuideWidget(); + } + return Super::RebuildWidget(); +} + +void UPlayBoardWidget::EnsureInputGuideWidget() +{ + if (IsDesignTime() || InputGuideText.IsValid() || !WidgetTree || !WidgetTree->RootWidget) + { + return; + } + + UOverlay* RootOverlay = Cast(WidgetTree->RootWidget); + if (!RootOverlay) + { + UWidget* OldRoot = WidgetTree->RootWidget; + RootOverlay = WidgetTree->ConstructWidget(UOverlay::StaticClass()); + if (RootOverlay) + { + RootOverlay->SetVisibility(ESlateVisibility::SelfHitTestInvisible); + WidgetTree->RootWidget = RootOverlay; + if (UOverlaySlot* OldRootSlot = RootOverlay->AddChildToOverlay(OldRoot)) + { + OldRootSlot->SetHorizontalAlignment(HAlign_Fill); + OldRootSlot->SetVerticalAlignment(VAlign_Fill); + } + } + } + + if (!RootOverlay) + { + return; + } + + UBorder* GuideBorder = WidgetTree->ConstructWidget(UBorder::StaticClass()); + UTextBlock* GuideText = WidgetTree->ConstructWidget(UTextBlock::StaticClass()); + if (!GuideBorder || !GuideText) + { + return; + } + + InputGuideBorder = GuideBorder; + InputGuideText = GuideText; + + GuideBorder->SetVisibility(ESlateVisibility::HitTestInvisible); + GuideBorder->SetPadding(FMargin(24.0f, 10.0f, 24.0f, 10.0f)); + FSlateBrush BannerBrush; + BannerBrush.DrawAs = ESlateBrushDrawType::RoundedBox; + BannerBrush.TintColor = FSlateColor(FLinearColor(0.05f, 0.08f, 0.14f, 0.78f)); + BannerBrush.OutlineSettings.CornerRadii = FVector4(12.0f, 12.0f, 12.0f, 12.0f); + BannerBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; + BannerBrush.OutlineSettings.Color = FSlateColor(FLinearColor(1.0f, 0.85f, 0.2f, 0.9f)); + BannerBrush.OutlineSettings.Width = 2.5f; + GuideBorder->SetBrush(BannerBrush); + GuideBorder->SetBrushColor(FLinearColor::White); + + GuideText->SetVisibility(ESlateVisibility::HitTestInvisible); + FSlateFontInfo GuideFont = CoinText ? CoinText->GetFont() : GuideText->GetFont(); + GuideFont.Size = 22; + GuideText->SetFont(GuideFont); + GuideText->SetColorAndOpacity(FSlateColor(FLinearColor(1.0f, 0.96f, 0.82f, 1.0f))); + GuideText->SetShadowOffset(FVector2D(1.5f, 1.5f)); + GuideText->SetShadowColorAndOpacity(FLinearColor(0.0f, 0.0f, 0.0f, 0.9f)); + GuideText->SetJustification(ETextJustify::Center); + + GuideBorder->SetContent(GuideText); + + if (UOverlaySlot* BannerSlot = RootOverlay->AddChildToOverlay(GuideBorder)) + { + BannerSlot->SetHorizontalAlignment(HAlign_Center); + BannerSlot->SetVerticalAlignment(VAlign_Top); + BannerSlot->SetPadding(FMargin(0.0f, 24.0f, 0.0f, 0.0f)); + } + + USizeBox* PadSizeBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + UBorder* PadBorder = WidgetTree->ConstructWidget(UBorder::StaticClass()); + UVerticalBox* PadVBox = WidgetTree->ConstructWidget(UVerticalBox::StaticClass()); + UImage* HandIconImage = WidgetTree->ConstructWidget(UImage::StaticClass()); + UTextBlock* PadLabel = WidgetTree->ConstructWidget(UTextBlock::StaticClass()); + + if (PadSizeBox && PadBorder && PadVBox && HandIconImage && PadLabel) + { + TouchDrivePadSizeBox = PadSizeBox; + TouchDrivePadBorder = PadBorder; + + PadSizeBox->SetVisibility(ESlateVisibility::HitTestInvisible); + PadSizeBox->SetWidthOverride(246.0f); + PadSizeBox->SetHeightOverride(246.0f); + + PadBorder->SetVisibility(ESlateVisibility::HitTestInvisible); + PadBorder->SetHorizontalAlignment(HAlign_Center); + PadBorder->SetVerticalAlignment(VAlign_Center); + PadBorder->SetPadding(FMargin(18.0f)); + + FSlateBrush PadBrush; + PadBrush.DrawAs = ESlateBrushDrawType::RoundedBox; + PadBrush.TintColor = FSlateColor(FLinearColor(0.04f, 0.07f, 0.14f, 0.72f)); + PadBrush.OutlineSettings.CornerRadii = FVector4(123.0f, 123.0f, 123.0f, 123.0f); + PadBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; + PadBrush.OutlineSettings.Color = FSlateColor(FLinearColor(1.0f, 0.85f, 0.2f, 0.9f)); + PadBrush.OutlineSettings.Width = 4.5f; + PadBorder->SetBrush(PadBrush); + PadBorder->SetBrushColor(FLinearColor::White); + + HandIconImage->SetVisibility(ESlateVisibility::HitTestInvisible); + if (const APlayerController* PC = GetOwningPlayer()) + { + if (ATrivialKartHUD* CurrentHUD = Cast(PC->GetHUD())) + { + if (UTexture2D* HandTex = CurrentHUD->GetOrCreateTouchHandTexture()) + { + HandIconImage->SetBrushFromTexture(HandTex, false); + } + } + } + HandIconImage->SetDesiredSizeOverride(FVector2D(114.0f, 114.0f)); + + PadLabel->SetVisibility(ESlateVisibility::HitTestInvisible); + FSlateFontInfo PadFont = CoinText ? CoinText->GetFont() : PadLabel->GetFont(); + PadFont.Size = 20; + PadLabel->SetFont(PadFont); + PadLabel->SetText(NSLOCTEXT("TrivialKart", "HoldToDrive", "HOLD TO\nDRIVE")); + PadLabel->SetColorAndOpacity(FSlateColor(FLinearColor(1.0f, 0.95f, 0.78f, 1.0f))); + PadLabel->SetShadowOffset(FVector2D(1.5f, 1.5f)); + PadLabel->SetShadowColorAndOpacity(FLinearColor(0.0f, 0.0f, 0.0f, 0.9f)); + PadLabel->SetJustification(ETextJustify::Center); + + if (UVerticalBoxSlot* IconSlot = PadVBox->AddChildToVerticalBox(HandIconImage)) + { + IconSlot->SetHorizontalAlignment(HAlign_Center); + } + if (UVerticalBoxSlot* LabelSlot = PadVBox->AddChildToVerticalBox(PadLabel)) + { + LabelSlot->SetHorizontalAlignment(HAlign_Center); + LabelSlot->SetPadding(FMargin(0.0f, 4.0f, 0.0f, 0.0f)); + } + + PadBorder->SetContent(PadVBox); + PadSizeBox->SetContent(PadBorder); + + if (UOverlaySlot* PadOverlaySlot = RootOverlay->AddChildToOverlay(PadSizeBox)) + { + PadOverlaySlot->SetHorizontalAlignment(HAlign_Right); + PadOverlaySlot->SetVerticalAlignment(VAlign_Center); + PadOverlaySlot->SetPadding(FMargin(0.0f, 0.0f, 48.0f, 0.0f)); + } + } +} + +void UPlayBoardWidget::UpdateInputGuideText(ETrivialKartInputMode InputMode) +{ + if (InputMode == ETrivialKartInputMode::Gamepad) + { + if (bFocusedByHover) + { + ClearMenuFocus(false); + } + } + else if (InputMode == ETrivialKartInputMode::Touch) + { + ClearMenuFocus(false); + } + else if (InputMode == ETrivialKartInputMode::KeyboardMouse) + { + const ATrivialKartPlayerController* PC = Cast(GetOwningPlayer()); + if (PC && !PC->IsKeyNavigationActive() && !bFocusedByHover) + { + ClearMenuFocus(true); + } + } + + EnsureInputGuideWidget(); + if (!InputGuideText.IsValid()) + { + return; + } + + if (LastRenderedGuideMode.IsSet() && LastRenderedGuideMode.GetValue() == InputMode) + { + return; + } + LastRenderedGuideMode = InputMode; + + const ESlateVisibility TouchPadVisibility = (InputMode == ETrivialKartInputMode::Touch) + ? ESlateVisibility::HitTestInvisible + : ESlateVisibility::Collapsed; + if (TouchDrivePadSizeBox.IsValid()) + { + TouchDrivePadSizeBox->SetVisibility(TouchPadVisibility); + } + if (TouchDrivePadBorder.IsValid()) + { + TouchDrivePadBorder->SetVisibility(TouchPadVisibility); + } + + switch (InputMode) + { + case ETrivialKartInputMode::Touch: + InputGuideText->SetText(NSLOCTEXT("TrivialKart", "GuideTouch", "Touch and hold to drive")); + break; + case ETrivialKartInputMode::Gamepad: + InputGuideText->SetText(NSLOCTEXT("TrivialKart", "GuideGamepad", "Hold Trigger, A, or D-Pad Right to drive")); + break; + case ETrivialKartInputMode::KeyboardMouse: + InputGuideText->SetText(NSLOCTEXT("TrivialKart", "GuideKeyboardMouse", "Hold Spacebar or Click to drive")); + break; + } +} void UPlayBoardWidget::NativeConstruct() { Super::NativeConstruct(); - GarageButton->OnClicked.AddUniqueDynamic(this, &ThisClass::OnGarageButtonClicked); - PGSButton->OnClicked.AddUniqueDynamic(this, &ThisClass::OnPGSButtonClicked); - StoreButton->OnClicked.AddUniqueDynamic(this, &ThisClass::OnStoreButtonClicked); + + LastRenderedGuideMode.Reset(); + EnsureInputGuideWidget(); + + // If RebuildWidget ran before HUD was ready, ensure the cached hand texture is assigned now + if (TouchDrivePadBorder.IsValid()) + { + if (UVerticalBox* PadVBox = Cast(TouchDrivePadBorder->GetContent())) + { + if (UImage* HandIconImage = Cast(PadVBox->GetChildAt(0))) + { + if (!HandIconImage->GetBrush().GetResourceObject()) + { + if (const APlayerController* PC = GetOwningPlayer()) + { + if (ATrivialKartHUD* CurrentHUD = Cast(PC->GetHUD())) + { + if (UTexture2D* HandTex = CurrentHUD->GetOrCreateTouchHandTexture()) + { + HandIconImage->SetBrushFromTexture(HandTex, false); + } + } + } + } + } + } + } + + if (WidgetTree) + { + WidgetTree->ForEachWidget([](UWidget* Widget) + { + if (!Widget || Widget->GetVisibility() != ESlateVisibility::Visible) + { + return; + } + if (Cast(Widget) || Cast(Widget)) + { + Widget->SetVisibility(ESlateVisibility::HitTestInvisible); + } + else if (Cast(Widget) || Cast(Widget) || Cast(Widget)) + { + Widget->SetVisibility(ESlateVisibility::SelfHitTestInvisible); + } + }); + } + + if (ATrivialKartPlayerController* PlayerController = Cast(GetOwningPlayer())) + { + PlayerController->OnInputModeUpdated.RemoveAll(this); + PlayerController->OnInputModeUpdated.AddUObject(this, &UPlayBoardWidget::UpdateInputGuideText); + UpdateInputGuideText(PlayerController->GetActiveInputMode()); + } +#if PLATFORM_ANDROID + else + { + UpdateInputGuideText(ETrivialKartInputMode::Touch); + } +#else + else + { + UpdateInputGuideText(ETrivialKartInputMode::KeyboardMouse); + } +#endif + + if (GarageButton) + { + GarageButton->OnClicked.AddUniqueDynamic(this, &ThisClass::OnGarageButtonClicked); + GarageButton->OnHovered.AddUniqueDynamic(this, &ThisClass::OnGarageButtonHovered); + GarageButton->OnUnhovered.AddUniqueDynamic(this, &ThisClass::OnMenuButtonUnhovered); + GarageButton->OnPressed.AddUniqueDynamic(this, &ThisClass::OnGarageButtonPressed); + GarageButton->OnReleased.AddUniqueDynamic(this, &ThisClass::OnMenuButtonReleased); + } + if (PGSButton) + { + PGSButton->OnClicked.AddUniqueDynamic(this, &ThisClass::OnPGSButtonClicked); + PGSButton->OnHovered.AddUniqueDynamic(this, &ThisClass::OnPGSButtonHovered); + PGSButton->OnUnhovered.AddUniqueDynamic(this, &ThisClass::OnMenuButtonUnhovered); + PGSButton->OnPressed.AddUniqueDynamic(this, &ThisClass::OnPGSButtonPressed); + PGSButton->OnReleased.AddUniqueDynamic(this, &ThisClass::OnMenuButtonReleased); + } + if (StoreButton) + { + StoreButton->OnClicked.AddUniqueDynamic(this, &ThisClass::OnStoreButtonClicked); + StoreButton->OnHovered.AddUniqueDynamic(this, &ThisClass::OnStoreButtonHovered); + StoreButton->OnUnhovered.AddUniqueDynamic(this, &ThisClass::OnMenuButtonUnhovered); + StoreButton->OnPressed.AddUniqueDynamic(this, &ThisClass::OnStoreButtonPressed); + StoreButton->OnReleased.AddUniqueDynamic(this, &ThisClass::OnMenuButtonReleased); + } - if (TWeakObjectPtr PlayerState = Cast(GetOwningPlayerState()); PlayerState.IsValid()) + if (!bStylesCached) + { + UButton* Buttons[3] = { GarageButton.Get(), PGSButton.Get(), StoreButton.Get() }; + for (int32 i = 0; i < 3; ++i) + { + if (Buttons[i]) + { + OriginalButtonStyles[i] = Buttons[i]->GetStyle(); + OriginalBackgroundColors[i] = Buttons[i]->GetBackgroundColor(); + } + } + bStylesCached = true; + } + + FocusedButtonIndex = -1; + PressedButtonIndex = -1; + bFocusedByHover = false; + UpdateButtonFocusVisuals(); + + if (TWeakObjectPtr PlayerState = Cast(GetOwningPlayerState()); PlayerState.IsValid()) { PlayerState->OnFuelUpdated.BindUObject(this, &UPlayBoardWidget::UpdateFuelBar); PlayerState->OnDistanceUpdated.BindUObject(this, &UPlayBoardWidget::UpdateDistanceText); @@ -45,24 +372,382 @@ void UPlayBoardWidget::NativeConstruct() void UPlayBoardWidget::NativeDestruct() { - GarageButton->OnClicked.RemoveDynamic(this, &ThisClass::OnGarageButtonClicked); - PGSButton->OnClicked.RemoveDynamic(this, &ThisClass::OnPGSButtonClicked); - StoreButton->OnClicked.RemoveDynamic(this, &ThisClass::OnStoreButtonClicked); + if (GarageButton) + { + GarageButton->OnClicked.RemoveDynamic(this, &ThisClass::OnGarageButtonClicked); + GarageButton->OnHovered.RemoveDynamic(this, &ThisClass::OnGarageButtonHovered); + GarageButton->OnUnhovered.RemoveDynamic(this, &ThisClass::OnMenuButtonUnhovered); + GarageButton->OnPressed.RemoveDynamic(this, &ThisClass::OnGarageButtonPressed); + GarageButton->OnReleased.RemoveDynamic(this, &ThisClass::OnMenuButtonReleased); + } + if (PGSButton) + { + PGSButton->OnClicked.RemoveDynamic(this, &ThisClass::OnPGSButtonClicked); + PGSButton->OnHovered.RemoveDynamic(this, &ThisClass::OnPGSButtonHovered); + PGSButton->OnUnhovered.RemoveDynamic(this, &ThisClass::OnMenuButtonUnhovered); + PGSButton->OnPressed.RemoveDynamic(this, &ThisClass::OnPGSButtonPressed); + PGSButton->OnReleased.RemoveDynamic(this, &ThisClass::OnMenuButtonReleased); + } + if (StoreButton) + { + StoreButton->OnClicked.RemoveDynamic(this, &ThisClass::OnStoreButtonClicked); + StoreButton->OnHovered.RemoveDynamic(this, &ThisClass::OnStoreButtonHovered); + StoreButton->OnUnhovered.RemoveDynamic(this, &ThisClass::OnMenuButtonUnhovered); + StoreButton->OnPressed.RemoveDynamic(this, &ThisClass::OnStoreButtonPressed); + StoreButton->OnReleased.RemoveDynamic(this, &ThisClass::OnMenuButtonReleased); + } + + if (ATrivialKartPlayerController* PlayerController = Cast(GetOwningPlayer())) + { + PlayerController->OnInputModeUpdated.RemoveAll(this); + } - if (TWeakObjectPtr PlayerState = Cast(GetOwningPlayerState()); PlayerState.IsValid()) + if (TWeakObjectPtr PlayerState = Cast(GetOwningPlayerState()); PlayerState.IsValid()) { - PlayerState->OnFuelUpdated.Unbind(); - PlayerState->OnDistanceUpdated.Unbind(); - PlayerState->OnCoinUpdated.Unbind(); + if (PlayerState->OnFuelUpdated.IsBoundToObject(this)) + { + PlayerState->OnFuelUpdated.Unbind(); + } + if (PlayerState->OnDistanceUpdated.IsBoundToObject(this)) + { + PlayerState->OnDistanceUpdated.Unbind(); + } + if (PlayerState->OnCoinUpdated.IsBoundToObject(this)) + { + PlayerState->OnCoinUpdated.Unbind(); + } } Super::NativeDestruct(); } +bool UPlayBoardWidget::IsAnyMenuButtonHovered() const +{ + return (GarageButton && GarageButton->IsHovered()) + || (PGSButton && PGSButton->IsHovered()) + || (StoreButton && StoreButton->IsHovered()); +} + +bool UPlayBoardWidget::IsPointOverAnyMenuButton(const FVector2D& ScreenSpacePosition) const +{ + const UButton* Buttons[3] = { GarageButton.Get(), PGSButton.Get(), StoreButton.Get() }; + for (const UButton* Btn : Buttons) + { + if (Btn && Btn->IsVisible() && Btn->GetCachedGeometry().IsUnderLocation(ScreenSpacePosition)) + { + return true; + } + } + return false; +} + +void UPlayBoardWidget::SetHoverFocus(int32 NewButtonIndex) +{ + const bool bWasUnfocused = (FocusedButtonIndex < 0); + FocusedButtonIndex = NewButtonIndex; + bFocusedByHover = true; + UpdateButtonFocusVisuals(); + + if (bWasUnfocused && FocusedButtonIndex >= 0) + { + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->LatchStickUntilNeutral(); + } + } +} + +void UPlayBoardWidget::SetKeyboardOrGamepadFocus(int32 NewButtonIndex) +{ + const bool bNeedStickLatch = (FocusedButtonIndex < 0) || bFocusedByHover; + PressedButtonIndex = -1; + FocusedButtonIndex = NewButtonIndex; + bFocusedByHover = false; + UpdateButtonFocusVisuals(); + + if (bNeedStickLatch && FocusedButtonIndex >= 0) + { + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->LatchStickUntilNeutral(); + } + } +} + +void UPlayBoardWidget::OnGarageButtonHovered() +{ + SetHoverFocus(0); +} + +void UPlayBoardWidget::OnPGSButtonHovered() +{ + SetHoverFocus(1); +} + +void UPlayBoardWidget::OnStoreButtonHovered() +{ + SetHoverFocus(2); +} + +void UPlayBoardWidget::OnMenuButtonUnhovered() +{ + if (!IsAnyMenuButtonHovered() && bFocusedByHover && PressedButtonIndex < 0) + { + ClearMenuFocus(false); + } +} + +void UPlayBoardWidget::OnGarageButtonPressed() +{ + FocusedButtonIndex = 0; + PressedButtonIndex = 0; + bFocusedByHover = true; + UpdateButtonFocusVisuals(); +} + +void UPlayBoardWidget::OnPGSButtonPressed() +{ + FocusedButtonIndex = 1; + PressedButtonIndex = 1; + bFocusedByHover = true; + UpdateButtonFocusVisuals(); +} + +void UPlayBoardWidget::OnStoreButtonPressed() +{ + FocusedButtonIndex = 2; + PressedButtonIndex = 2; + bFocusedByHover = true; + UpdateButtonFocusVisuals(); +} + +void UPlayBoardWidget::OnMenuButtonReleased() +{ + PressedButtonIndex = -1; + if (bFocusedByHover && !IsAnyMenuButtonHovered()) + { + ClearMenuFocus(false); + } + else + { + UpdateButtonFocusVisuals(); + } + + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->RestoreFocusToGameViewport(); + } +} + +void UPlayBoardWidget::ClearMenuFocus(bool bOnlyIfNotHovered) +{ + if (bOnlyIfNotHovered && IsAnyMenuButtonHovered()) + { + return; + } + const bool bHadFocus = (FocusedButtonIndex >= 0 || PressedButtonIndex >= 0); + if (bHadFocus) + { + FocusedButtonIndex = -1; + PressedButtonIndex = -1; + bFocusedByHover = false; + UpdateButtonFocusVisuals(); + } + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + if (bHadFocus) + { + PC->LatchStickUntilNeutral(); + } + PC->RestoreFocusToGameViewport(); + } +} + +void UPlayBoardWidget::CancelPendingPress() +{ + if (PressedButtonIndex >= 0) + { + PressedButtonIndex = -1; + UpdateButtonFocusVisuals(); + } +} + +void UPlayBoardWidget::OnViewportPointerDown(const FVector2D& ScreenSpacePosition) +{ + if (!IsPointOverAnyMenuButton(ScreenSpacePosition)) + { + ClearMenuFocus(false); + } +} + +bool UPlayBoardWidget::HandleGamepadKey(const FKey& Key, bool bIsPressed, bool bIsRepeat) +{ + if (!bIsPressed) + { + if (Key == EKeys::Gamepad_FaceButton_Bottom) + { + if (PressedButtonIndex >= 0 && PressedButtonIndex == FocusedButtonIndex && FocusedButtonIndex <= 2) + { + const int32 TargetButton = FocusedButtonIndex; + PressedButtonIndex = -1; + UpdateButtonFocusVisuals(); + if (TargetButton == 0) + { + OnGarageButtonClicked(); + } + else if (TargetButton == 1) + { + OnPGSButtonClicked(); + } + else if (TargetButton == 2) + { + OnStoreButtonClicked(); + } + return true; + } + CancelPendingPress(); + } + return false; + } + + if (Key == EKeys::Gamepad_DPad_Down || Key == EKeys::Gamepad_DPad_Up) + { + if (!bIsRepeat) + { + if (FocusedButtonIndex < 0 || bFocusedByHover) + { + SetKeyboardOrGamepadFocus(FocusedButtonIndex >= 0 ? FocusedButtonIndex : 0); + } + else + { + ClearMenuFocus(false); + } + } + return true; + } + + if (Key == EKeys::Gamepad_FaceButton_Right) + { + if (FocusedButtonIndex >= 0) + { + ClearMenuFocus(false); + return true; + } + return false; + } + + if (Key == EKeys::Gamepad_FaceButton_Bottom) + { + if (FocusedButtonIndex >= 0 && FocusedButtonIndex <= 2 && !bFocusedByHover) + { + PressedButtonIndex = FocusedButtonIndex; + UpdateButtonFocusVisuals(); + return true; + } + return false; + } + + if (Key == EKeys::Gamepad_LeftShoulder) + { + SetKeyboardOrGamepadFocus((FocusedButtonIndex < 0 || bFocusedByHover) ? 0 : (FocusedButtonIndex + 2) % 3); + return true; + } + if (Key == EKeys::Gamepad_RightShoulder) + { + SetKeyboardOrGamepadFocus((FocusedButtonIndex < 0 || bFocusedByHover) ? 0 : (FocusedButtonIndex + 1) % 3); + return true; + } + + if (Key == EKeys::Gamepad_DPad_Left) + { + if (FocusedButtonIndex >= 0 && !bFocusedByHover) + { + SetKeyboardOrGamepadFocus((FocusedButtonIndex + 2) % 3); + } + return true; + } + if (Key == EKeys::Gamepad_DPad_Right) + { + if (FocusedButtonIndex >= 0 && !bFocusedByHover) + { + SetKeyboardOrGamepadFocus((FocusedButtonIndex + 1) % 3); + return true; + } + if (bFocusedByHover) + { + ClearMenuFocus(false); + } + return false; + } + + if (Key == EKeys::Gamepad_RightTrigger || Key == EKeys::Gamepad_LeftTrigger) + { + if (FocusedButtonIndex >= 0) + { + ClearMenuFocus(false); + } + return false; + } + + return false; +} + +void UPlayBoardWidget::UpdateButtonFocusVisuals() +{ + UButton* Buttons[3] = { GarageButton.Get(), PGSButton.Get(), StoreButton.Get() }; + + for (int32 i = 0; i < 3; ++i) + { + if (!Buttons[i]) + { + continue; + } + Buttons[i]->SetRenderTransformPivot(FVector2D(0.5f, 0.5f)); + if (i == FocusedButtonIndex) + { + const bool bIsPressed = (i == PressedButtonIndex) || Buttons[i]->IsPressed(); + FSlateBrush HighlightBrush; + HighlightBrush.DrawAs = ESlateBrushDrawType::RoundedBox; + HighlightBrush.TintColor = FSlateColor(bIsPressed + ? FLinearColor(1.0f, 0.35f, 0.0f, 0.68f) + : FLinearColor(1.0f, 0.45f, 0.0f, 0.48f)); + HighlightBrush.OutlineSettings.CornerRadii = FVector4(12.0f, 12.0f, 12.0f, 12.0f); + HighlightBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; + HighlightBrush.OutlineSettings.Color = FSlateColor(FLinearColor(1.0f, 0.9f, 0.0f, 1.0f)); + HighlightBrush.OutlineSettings.Width = 6.0f; + + FButtonStyle FocusedStyle = OriginalButtonStyles[i]; + FocusedStyle.SetNormal(HighlightBrush); + FocusedStyle.SetHovered(HighlightBrush); + FocusedStyle.SetPressed(HighlightBrush); + Buttons[i]->SetStyle(FocusedStyle); + Buttons[i]->SetBackgroundColor(FLinearColor::White); + Buttons[i]->SetColorAndOpacity(FLinearColor::White); + const float TargetScale = bIsPressed ? 0.88f : 1.12f; + Buttons[i]->SetRenderScale(FVector2D(TargetScale, TargetScale)); + } + else + { + Buttons[i]->SetStyle(OriginalButtonStyles[i]); + Buttons[i]->SetBackgroundColor(OriginalBackgroundColors[i]); + Buttons[i]->SetColorAndOpacity(FLinearColor::White); + Buttons[i]->SetRenderScale(FVector2D(1.0f, 1.0f)); + } + } + + if (const APlayerController* PlayerController = GetOwningPlayer()) + { + if (const ATrivialKartHUD* CurrentHUD = Cast(PlayerController->GetHUD())) + { + CurrentHUD->SyncGameplayInputContext(); + } + } +} + void UPlayBoardWidget::OnGarageButtonClicked() { - if (TWeakObjectPtr PlayerController = GetOwningPlayer(); PlayerController.IsValid()) + if (TWeakObjectPtr PlayerController = GetOwningPlayer(); PlayerController.IsValid()) { - if (const TWeakObjectPtr CurrentHUD = Cast(PlayerController->GetHUD()); + if (const TWeakObjectPtr CurrentHUD = Cast(PlayerController->GetHUD()); CurrentHUD.IsValid()) { CurrentHUD->AddWidgetToScreen(EWidgetType::Garage); @@ -73,9 +758,9 @@ void UPlayBoardWidget::OnGarageButtonClicked() void UPlayBoardWidget::OnPGSButtonClicked() { - if (TWeakObjectPtr PlayerController = GetOwningPlayer(); PlayerController.IsValid()) + if (TWeakObjectPtr PlayerController = GetOwningPlayer(); PlayerController.IsValid()) { - if (const TWeakObjectPtr CurrentHUD = Cast(PlayerController->GetHUD()); + if (const TWeakObjectPtr CurrentHUD = Cast(PlayerController->GetHUD()); CurrentHUD.IsValid()) { CurrentHUD->AddWidgetToScreen(EWidgetType::PGS); @@ -86,9 +771,9 @@ void UPlayBoardWidget::OnPGSButtonClicked() void UPlayBoardWidget::OnStoreButtonClicked() { - if (TWeakObjectPtr PlayerController = GetOwningPlayer(); PlayerController.IsValid()) + if (TWeakObjectPtr PlayerController = GetOwningPlayer(); PlayerController.IsValid()) { - if (const TWeakObjectPtr CurrentHUD = Cast(PlayerController->GetHUD()); + if (const TWeakObjectPtr CurrentHUD = Cast(PlayerController->GetHUD()); CurrentHUD.IsValid()) { CurrentHUD->AddWidgetToScreen(EWidgetType::Store); @@ -99,15 +784,24 @@ void UPlayBoardWidget::OnStoreButtonClicked() void UPlayBoardWidget::UpdateFuelBar(const float FuelBarPercentage) const { - FuelBar->SetPercent(FuelBarPercentage); + if (FuelBar) + { + FuelBar->SetPercent(FuelBarPercentage); + } } void UPlayBoardWidget::UpdateDistanceText(const float Distance) const { - DistanceText->SetText(FText::FromString(FString::FromInt(FMath::RoundToInt(Distance)))); + if (DistanceText) + { + DistanceText->SetText(FText::FromString(FString::FromInt(FMath::RoundToInt(Distance)))); + } } void UPlayBoardWidget::UpdateCoinText(const int Quantity) const { - CoinText->SetText(FText::FromString(FString::FromInt(Quantity))); + if (CoinText) + { + CoinText->SetText(FText::FromString(FString::FromInt(Quantity))); + } } diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/SelectableItem.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/SelectableItem.cpp index 7e21b556..74a88d05 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/SelectableItem.cpp +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/SelectableItem.cpp @@ -17,7 +17,12 @@ #include "Widgets/SelectableItem.h" #include "Actors/KartPawn.h" +#include "Blueprint/WidgetTree.h" +#include "Components/Border.h" #include "Components/Button.h" +#include "Components/Overlay.h" +#include "Components/OverlaySlot.h" +#include "Controllers/TrivialKartPlayerController.h" #include "GameInstances/TrivialKartGameInstance.h" #include "Infos/TrivialKartPlayerState.h" #include "Objects/TrivialKartSaveGame.h" @@ -25,30 +30,49 @@ void USelectableItem::NativePreConstruct() { Super::NativePreConstruct(); - SelectionButton->SetStyle(SelectionButtonStyle); + if (SelectionButton) + { + SelectionButton->SetStyle(SelectionButtonStyle); + } } void USelectableItem::NativeConstruct() { Super::NativeConstruct(); - SelectionButton->OnClicked.AddUniqueDynamic(this, &USelectableItem::OnSelectionButtonClicked); - if (const TWeakObjectPtr Instance = Cast(GetGameInstance()); - Instance.IsValid()) + if (SelectionButton) + { + SelectionButton->OnClicked.AddUniqueDynamic(this, &USelectableItem::OnSelectionButtonClicked); + SelectionButton->OnHovered.AddUniqueDynamic(this, &USelectableItem::OnSelectionButtonHovered); + SelectionButton->OnUnhovered.AddUniqueDynamic(this, &USelectableItem::OnSelectionButtonUnhovered); + SelectionButton->OnPressed.AddUniqueDynamic(this, &USelectableItem::OnSelectionButtonPressed); + SelectionButton->OnReleased.AddUniqueDynamic(this, &USelectableItem::OnSelectionButtonReleased); + } + + EnsureOverlayHitTestAndBorder(); + RefreshOwnershipState(); +} + +void USelectableItem::RefreshOwnershipState() +{ + if (CarType.IsEmpty()) + { + return; + } + if (const TWeakObjectPtr Instance = Cast(GetGameInstance()); + Instance.IsValid()) { - if (TWeakObjectPtr Save = Instance->LoadGame(); Save.IsValid()) + if (TWeakObjectPtr Save = Instance->LoadGame(); Save.IsValid()) { - bool bIsOwned = Save->CarsOwned.Contains(CarType); + const bool bIsOwned = Save->CarsOwned.Contains(CarType); switch (SelectionOperationType) { case ESelectableOperationType::CoinPurchase: - { - SetIsEnabled(!bIsOwned); - } + SetIsEnabled(!bIsOwned); break; case ESelectableOperationType::ObjectSelection: - { - SetVisibility(bIsOwned ? ESlateVisibility::Visible : ESlateVisibility::Collapsed); - } + SetVisibility(bIsOwned ? ESlateVisibility::Visible : ESlateVisibility::Collapsed); + break; + default: break; } } @@ -57,12 +81,104 @@ void USelectableItem::NativeConstruct() void USelectableItem::NativeDestruct() { - SelectionButton->OnClicked.RemoveDynamic(this, &USelectableItem::OnSelectionButtonClicked); + if (SelectionButton) + { + SelectionButton->OnClicked.RemoveDynamic(this, &USelectableItem::OnSelectionButtonClicked); + SelectionButton->OnHovered.RemoveDynamic(this, &USelectableItem::OnSelectionButtonHovered); + SelectionButton->OnUnhovered.RemoveDynamic(this, &USelectableItem::OnSelectionButtonUnhovered); + SelectionButton->OnPressed.RemoveDynamic(this, &USelectableItem::OnSelectionButtonPressed); + SelectionButton->OnReleased.RemoveDynamic(this, &USelectableItem::OnSelectionButtonReleased); + } Super::NativeDestruct(); } +void USelectableItem::EnsureOverlayHitTestAndBorder() +{ + if (UOverlay* CardOverlay = Cast(GetParent())) + { + if (CardOverlay->GetVisibility() == ESlateVisibility::Visible) + { + CardOverlay->SetVisibility(ESlateVisibility::SelfHitTestInvisible); + } + for (int32 i = 0; i < CardOverlay->GetChildrenCount(); ++i) + { + UWidget* Sibling = CardOverlay->GetChildAt(i); + if (Sibling && Sibling != this && Sibling != FocusHighlightBorder && Sibling->IsVisible()) + { + Sibling->SetVisibility(ESlateVisibility::HitTestInvisible); + } + } + } + + if (!FocusHighlightBorder && WidgetTree && SelectionButton) + { + if (UOverlay* ButtonOverlay = Cast(SelectionButton->GetParent())) + { + FocusHighlightBorder = WidgetTree->ConstructWidget(UBorder::StaticClass()); + if (FocusHighlightBorder) + { + FocusHighlightBorder->SetVisibility(ESlateVisibility::Collapsed); + FocusHighlightBorder->SetPadding(FMargin(0.0f)); + if (UOverlaySlot* OverlaySlot = ButtonOverlay->AddChildToOverlay(FocusHighlightBorder)) + { + OverlaySlot->SetHorizontalAlignment(HAlign_Fill); + OverlaySlot->SetVerticalAlignment(VAlign_Fill); + } + } + } + } +} + +UWidget* USelectableItem::GetVisualScaleTarget() const +{ + if (UOverlay* CardOverlay = Cast(GetParent())) + { + return CardOverlay; + } + return const_cast(this); +} + +void USelectableItem::OnSelectionButtonHovered() +{ + if (IsItemSelectable() && (!SelectionButton || !SelectionButton->IsPressed())) + { + OnItemInteracted.ExecuteIfBound(this); + } +} + +void USelectableItem::OnSelectionButtonUnhovered() +{ + OnItemUnhovered.ExecuteIfBound(this); +} + +void USelectableItem::OnSelectionButtonPressed() +{ + if (IsItemSelectable()) + { + SetButtonPressed(true); + OnItemInteracted.ExecuteIfBound(this); + } +} + +void USelectableItem::OnSelectionButtonReleased() +{ + SetButtonPressed(false); + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->RestoreFocusToGameViewport(); + } +} + +void USelectableItem::SetButtonPressed(bool bInPressed) +{ + bIsButtonPressed = bInPressed; + UpdateHighlightVisuals(); +} + void USelectableItem::OnSelectionButtonClicked() { + SetButtonPressed(false); + switch (SelectionOperationType) { case ESelectableOperationType::InAppPurchase: @@ -71,18 +187,17 @@ void USelectableItem::OnSelectionButtonClicked() switch (PurchaseObject) { case EPurchaseObject::Coin: - if (PurchaseObject == EPurchaseObject::Coin) - { - if (const TWeakObjectPtr PlayerState = Cast(GetOwningPlayerState()); + if (const TWeakObjectPtr PlayerState = Cast(GetOwningPlayerState()); PlayerState.IsValid()) - { - PlayerState->AddCoins(PurchaseQuantity); - } + { + PlayerState->AddCoins(PurchaseQuantity); } break; + default: + break; } #endif - if (const TWeakObjectPtr Instance = Cast(GetGameInstance()); + if (const TWeakObjectPtr Instance = Cast(GetGameInstance()); Instance.IsValid()) { Instance->StartPurchasing(PurchaseID, PurchaseQuantity, bIsConsumable); @@ -91,7 +206,7 @@ void USelectableItem::OnSelectionButtonClicked() break; case ESelectableOperationType::CoinPurchase: { - if (const TWeakObjectPtr PlayerState = Cast(GetOwningPlayerState()); + if (const TWeakObjectPtr PlayerState = Cast(GetOwningPlayerState()); PlayerState.IsValid()) { if (PlayerState->GetCoinCount() >= CoinQuantity) @@ -99,20 +214,20 @@ void USelectableItem::OnSelectionButtonClicked() switch (PurchaseObject) { case EPurchaseObject::Car: + if (!CarType.IsEmpty()) { - if (CarType.IsEmpty()) - return; PlayerState->AddCarToInventory(CarType); SetIsEnabled(false); + PlayerState->ConsumeCoins(CoinQuantity); } break; case EPurchaseObject::Fuel: - { - PlayerState->Refuel(); - } + PlayerState->Refuel(); + PlayerState->ConsumeCoins(CoinQuantity); + break; + default: break; } - PlayerState->ConsumeCoins(CoinQuantity); } } } @@ -121,14 +236,14 @@ void USelectableItem::OnSelectionButtonClicked() { if (IsValid(GetOwningPlayer())) { - if (TWeakObjectPtr Pawn = Cast(GetOwningPlayer()->GetPawn()); + if (TWeakObjectPtr Pawn = Cast(GetOwningPlayer()->GetPawn()); Pawn.IsValid()) { Pawn->SwitchCar(CarType); - if (const TWeakObjectPtr Instance = Cast(GetGameInstance()); + if (const TWeakObjectPtr Instance = Cast(GetGameInstance()); Instance.IsValid()) { - if (TWeakObjectPtr Save = Instance->LoadGame(); Save.IsValid()) + if (TWeakObjectPtr Save = Instance->LoadGame(); Save.IsValid()) { Save->ActiveCarType = CarType; Instance->SaveGame(Save.Get()); @@ -138,5 +253,80 @@ void USelectableItem::OnSelectionButtonClicked() } } break; + default: + break; + } + + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->RestoreFocusToGameViewport(); + } + + OnItemClicked.ExecuteIfBound(this); +} + +void USelectableItem::SetGamepadFocused(bool bInFocused, bool bInShowVisual) +{ + bIsGamepadFocused = bInFocused; + bShowFocusVisual = bInShowVisual; + UpdateHighlightVisuals(); +} + +void USelectableItem::UpdateHighlightVisuals() +{ + if (!SelectionButton) + { + return; + } + + EnsureOverlayHitTestAndBorder(); + + UWidget* ScaleTarget = GetVisualScaleTarget(); + ScaleTarget->SetRenderTransformPivot(FVector2D(0.5f, 0.5f)); + if (ScaleTarget != this) + { + SetRenderScale(FVector2D(1.0f, 1.0f)); + } + + const bool bShowHighlight = (bIsGamepadFocused && bShowFocusVisual && IsItemSelectable()) || bIsButtonPressed; + if (bShowHighlight) + { + if (FocusHighlightBorder) + { + FSlateBrush OverlayBrush; + OverlayBrush.DrawAs = ESlateBrushDrawType::RoundedBox; + OverlayBrush.TintColor = FSlateColor(bIsButtonPressed + ? FLinearColor(1.0f, 0.30f, 0.0f, 0.72f) + : FLinearColor(1.0f, 0.45f, 0.0f, 0.48f)); + OverlayBrush.OutlineSettings.CornerRadii = FVector4(12.0f, 12.0f, 12.0f, 12.0f); + OverlayBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; + OverlayBrush.OutlineSettings.Color = FSlateColor(bIsButtonPressed + ? FLinearColor(1.0f, 1.0f, 0.2f, 1.0f) + : FLinearColor(1.0f, 0.9f, 0.0f, 1.0f)); + OverlayBrush.OutlineSettings.Width = bIsButtonPressed ? 10.0f : 8.0f; + FocusHighlightBorder->SetBrush(OverlayBrush); + FocusHighlightBorder->SetBrushColor(FLinearColor::White); + FocusHighlightBorder->SetVisibility(ESlateVisibility::HitTestInvisible); + } + const float TargetScale = bIsButtonPressed ? 0.88f : 1.08f; + ScaleTarget->SetRenderScale(FVector2D(TargetScale, TargetScale)); + } + else + { + if (FocusHighlightBorder) + { + FocusHighlightBorder->SetVisibility(ESlateVisibility::Collapsed); + } + ScaleTarget->SetRenderScale(FVector2D(1.0f, 1.0f)); } } + +bool USelectableItem::IsButtonHovered() const +{ + return SelectionButton && SelectionButton->IsHovered(); +} + +bool USelectableItem::IsItemSelectable() const +{ + return IsVisible() && GetIsEnabled() && SelectionButton && SelectionButton->GetIsEnabled(); +} diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/StoreWidget.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/StoreWidget.cpp index 91fd105c..f91ecffd 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/StoreWidget.cpp +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/StoreWidget.cpp @@ -17,42 +17,195 @@ #include "Widgets/StoreWidget.h" #include "Actors/TrivialKartHUD.h" +#include "Blueprint/WidgetTree.h" +#include "Components/Border.h" #include "Components/Button.h" #include "Components/CheckBox.h" +#include "Components/HorizontalBox.h" +#include "Components/Image.h" +#include "Components/Overlay.h" +#include "Components/OverlaySlot.h" +#include "Components/PanelWidget.h" +#include "Components/ScrollBox.h" +#include "Components/TextBlock.h" +#include "Components/VerticalBox.h" #include "Components/WidgetSwitcher.h" +#include "Widgets/SelectableItem.h" + +static UBorder* EnsureTabHighlightBorder(UWidgetTree* WidgetTree, UCheckBox* CB) +{ + UOverlay* ParentOverlay = CB ? Cast(CB->GetParent()) : nullptr; + if (!WidgetTree || !ParentOverlay) + { + return nullptr; + } + + UBorder* Border = WidgetTree->ConstructWidget(UBorder::StaticClass()); + Border->SetVisibility(ESlateVisibility::Collapsed); + Border->SetPadding(FMargin(0.0f)); + if (UOverlaySlot* OverlaySlot = ParentOverlay->AddChildToOverlay(Border)) + { + OverlaySlot->SetHorizontalAlignment(HAlign_Fill); + OverlaySlot->SetVerticalAlignment(VAlign_Fill); + } + return Border; +} void UStoreWidget::NativeConstruct() { Super::NativeConstruct(); + + // Keep the modal root hit-testable so empty modal space blocks clicks from piercing into FSceneViewport + SetVisibility(ESlateVisibility::Visible); + + if (WidgetTree) + { + UWidget* TreeRoot = WidgetTree->RootWidget; + WidgetTree->ForEachWidget([TreeRoot](UWidget* Widget) + { + if (!Widget || Widget == TreeRoot || Widget->GetVisibility() != ESlateVisibility::Visible) + { + return; + } + if (Cast(Widget) || Cast(Widget)) + { + Widget->SetVisibility(ESlateVisibility::HitTestInvisible); + } + else if (Cast(Widget) || Cast(Widget) || Cast(Widget)) + { + Widget->SetVisibility(ESlateVisibility::SelfHitTestInvisible); + } + }); + } - BackButton->OnClicked.AddUniqueDynamic(this, &UStoreWidget::OnBackButtonClicked); + if (BackButton) + { + if (!bBackStyleCached) + { + OriginalBackButtonStyle = BackButton->GetStyle(); + OriginalBackButtonBgColor = BackButton->GetBackgroundColor(); + bBackStyleCached = true; + } + BackButton->OnClicked.AddUniqueDynamic(this, &UStoreWidget::OnBackButtonClicked); + BackButton->OnReleased.AddUniqueDynamic(this, &UStoreWidget::OnBackButtonReleased); + } + CheckBoxes.Empty(); CheckBoxes.Add(FuelCheckBox); CheckBoxes.Add(CoinCheckBox); CheckBoxes.Add(CarCheckBox); CheckBoxes.Add(SubscriptionCheckBox); - FuelCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UStoreWidget::OnFuelBoxStateChanged); - CoinCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UStoreWidget::OnCoinBoxStateChange); - CarCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UStoreWidget::OnCarBoxStateChange); - SubscriptionCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UStoreWidget::OnSubscriptionBoxStateChange); + + if (TabHighlightBorders.Num() != CheckBoxes.Num()) + { + TabHighlightBorders.Empty(); + for (UCheckBox* CB : CheckBoxes) + { + TabHighlightBorders.Add(EnsureTabHighlightBorder(WidgetTree, CB)); + } + } + + if (FuelCheckBox) + { + FuelCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UStoreWidget::OnFuelBoxStateChanged); + } + if (CoinCheckBox) + { + CoinCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UStoreWidget::OnCoinBoxStateChange); + } + if (CarCheckBox) + { + CarCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UStoreWidget::OnCarBoxStateChange); + } + if (SubscriptionCheckBox) + { + SubscriptionCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UStoreWidget::OnSubscriptionBoxStateChange); + } + + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->OnInputModeUpdated.RemoveAll(this); + PC->OnInputModeUpdated.AddUObject(this, &UStoreWidget::OnInputModeChanged); + } + + GamepadPressedItem.Reset(); + HoveredItem.Reset(); + bBackButtonPressed = false; + RefreshAllItemsOwnership(); + ActiveTabIndex = ContentSwitcher ? ContentSwitcher->GetActiveWidgetIndex() : 0; + FocusedItemIndex = 0; + RefreshGamepadFocus(false); } void UStoreWidget::NativeDestruct() { - BackButton->OnClicked.RemoveDynamic(this, &UStoreWidget::OnBackButtonClicked); - FuelCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UStoreWidget::OnFuelBoxStateChanged); - CoinCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UStoreWidget::OnCoinBoxStateChange); - CarCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UStoreWidget::OnCarBoxStateChange); - SubscriptionCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UStoreWidget::OnSubscriptionBoxStateChange); + if (BackButton) + { + BackButton->OnClicked.RemoveDynamic(this, &UStoreWidget::OnBackButtonClicked); + BackButton->OnReleased.RemoveDynamic(this, &UStoreWidget::OnBackButtonReleased); + } + if (FuelCheckBox) + { + FuelCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UStoreWidget::OnFuelBoxStateChanged); + } + if (CoinCheckBox) + { + CoinCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UStoreWidget::OnCoinBoxStateChange); + } + if (CarCheckBox) + { + CarCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UStoreWidget::OnCarBoxStateChange); + } + if (SubscriptionCheckBox) + { + SubscriptionCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UStoreWidget::OnSubscriptionBoxStateChange); + } + + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->OnInputModeUpdated.RemoveAll(this); + } + CheckBoxes.Empty(); Super::NativeDestruct(); } +bool UStoreWidget::IsNavigationVisualActive() const +{ + if (const ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + return PC->IsKeyNavigationActive(); + } + return false; +} + +void UStoreWidget::RestoreViewportFocus() const +{ + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->RestoreFocusToGameViewport(); + } +} + +void UStoreWidget::OnInputModeChanged(ETrivialKartInputMode NewInputMode) +{ + if (!IsNavigationVisualActive()) + { + CancelPendingPress(); + } + RefreshGamepadFocus(false); +} + +void UStoreWidget::OnBackButtonReleased() +{ + RestoreViewportFocus(); +} + void UStoreWidget::OnBackButtonClicked() { - if (TWeakObjectPtr PlayerController = GetOwningPlayer(); PlayerController.IsValid()) + if (TWeakObjectPtr PlayerController = GetOwningPlayer(); PlayerController.IsValid()) { - if (const TWeakObjectPtr CurrentHUD = Cast(PlayerController->GetHUD()); + if (const TWeakObjectPtr CurrentHUD = Cast(PlayerController->GetHUD()); CurrentHUD.IsValid()) { CurrentHUD->AddWidgetToScreen(EWidgetType::PlayBoard); @@ -64,13 +217,22 @@ void UStoreWidget::OnBackButtonClicked() void UStoreWidget::SetCheckBoxState(bool bIsChecked, UCheckBox* CheckBox, int ActiveWidgetIndex) { if (CheckBox == nullptr) + { return; + } + CancelPendingPress(); + HoveredItem.Reset(); + FocusedItemIndex = -1; if (bIsChecked) { - ContentSwitcher->SetActiveWidgetIndex(ActiveWidgetIndex); + ActiveTabIndex = ActiveWidgetIndex; + if (ContentSwitcher) + { + ContentSwitcher->SetActiveWidgetIndex(ActiveWidgetIndex); + } for (auto CurrentCheckBox : CheckBoxes) { - if (CurrentCheckBox != CheckBox) + if (CurrentCheckBox && CurrentCheckBox != CheckBox) { CurrentCheckBox->SetCheckedState(ECheckBoxState::Unchecked); } @@ -80,6 +242,442 @@ void UStoreWidget::SetCheckBoxState(bool bIsChecked, UCheckBox* CheckBox, int Ac { CheckBox->SetCheckedState(ECheckBoxState::Checked); } + RefreshAllItemsOwnership(); + RefreshGamepadFocus(false); + RestoreViewportFocus(); +} + +void UStoreWidget::SelectTabByIndex(int32 NewTabIndex) +{ + if (CheckBoxes.Num() == 0) + { + return; + } + ActiveTabIndex = (NewTabIndex + CheckBoxes.Num()) % CheckBoxes.Num(); + if (UCheckBox* TargetCheckBox = CheckBoxes[ActiveTabIndex]) + { + TargetCheckBox->SetCheckedState(ECheckBoxState::Checked); + SetCheckBoxState(true, TargetCheckBox, ActiveTabIndex); + } +} + +void UStoreWidget::RefreshAllItemsOwnership() const +{ + TArray AllItems; + GatherSelectableItems(ContentSwitcher, AllItems, false); + for (USelectableItem* Item : AllItems) + { + if (Item) + { + Item->RefreshOwnershipState(); + } + } +} + +void UStoreWidget::GatherSelectableItems(UWidget* RootWidget, TArray& OutItems, bool bOnlySelectable) const +{ + if (!RootWidget) + { + return; + } + if (USelectableItem* Item = Cast(RootWidget)) + { + if (!bOnlySelectable || Item->IsItemSelectable()) + { + OutItems.Add(Item); + } + return; + } + if (bOnlySelectable && !RootWidget->IsVisible()) + { + return; + } + if (UPanelWidget* Panel = Cast(RootWidget)) + { + for (int32 i = 0; i < Panel->GetChildrenCount(); ++i) + { + GatherSelectableItems(Panel->GetChildAt(i), OutItems, bOnlySelectable); + } + } +} + +void UStoreWidget::OnSelectableItemInteracted(USelectableItem* InteractedItem) +{ + HoveredItem = InteractedItem; + TArray ActiveItems; + if (ContentSwitcher) + { + GatherSelectableItems(ContentSwitcher->GetActiveWidget(), ActiveItems, true); + } + const int32 FoundIndex = ActiveItems.IndexOfByKey(InteractedItem); + if (FoundIndex != INDEX_NONE) + { + FocusedItemIndex = FoundIndex; + } + RefreshGamepadFocus(false); +} + +void UStoreWidget::OnSelectableItemUnhovered(USelectableItem* UnhoveredItem) +{ + if (HoveredItem.Get() == UnhoveredItem) + { + HoveredItem.Reset(); + if (!IsNavigationVisualActive()) + { + RefreshGamepadFocus(false); + } + } +} + +void UStoreWidget::OnSelectableItemClicked(USelectableItem* ClickedItem) +{ + RefreshAllItemsOwnership(); + if (ClickedItem && !ClickedItem->IsItemSelectable()) + { + HoveredItem.Reset(); + RefreshGamepadFocus(false); + } + else + { + OnSelectableItemInteracted(ClickedItem); + } +} + +void UStoreWidget::RefreshOwnershipAndFocus(bool bScrollIntoView) +{ + RefreshAllItemsOwnership(); + RefreshGamepadFocus(bScrollIntoView); +} + +void UStoreWidget::CancelPendingPress() +{ + if (USelectableItem* PressedItem = GamepadPressedItem.Get()) + { + PressedItem->SetButtonPressed(false); + } + GamepadPressedItem.Reset(); + if (bBackButtonPressed) + { + bBackButtonPressed = false; + RefreshGamepadFocus(false); + } +} + +void UStoreWidget::RefreshGamepadFocus(bool bScrollIntoView) +{ + const ATrivialKartPlayerController* PC = Cast(GetOwningPlayer()); + const bool bShowNavVisual = IsNavigationVisualActive(); + const bool bAllowMouseHoverVisual = (!bShowNavVisual && PC && PC->GetActiveInputMode() == ETrivialKartInputMode::KeyboardMouse); + + TArray ActiveItems; + if (ContentSwitcher) + { + GatherSelectableItems(ContentSwitcher->GetActiveWidget(), ActiveItems, true); + } + + USelectableItem* FocusedItem = nullptr; + if (ActiveItems.Num() == 0 && FocusedItemIndex >= 0) + { + FocusedItemIndex = -1; + } + else if (FocusedItemIndex >= 0) + { + FocusedItemIndex = FMath::Clamp(FocusedItemIndex, 0, ActiveItems.Num() - 1); + FocusedItem = ActiveItems[FocusedItemIndex]; + } + + TArray AllItems; + GatherSelectableItems(ContentSwitcher, AllItems, false); + for (USelectableItem* Item : AllItems) + { + if (Item) + { + const bool bIsInActiveTab = ActiveItems.Contains(Item); + Item->OnItemInteracted.BindUObject(this, &UStoreWidget::OnSelectableItemInteracted); + Item->OnItemUnhovered.BindUObject(this, &UStoreWidget::OnSelectableItemUnhovered); + Item->OnItemClicked.BindUObject(this, &UStoreWidget::OnSelectableItemClicked); + if (!bIsInActiveTab || (Item != GamepadPressedItem.Get() && !Item->IsButtonHovered())) + { + Item->SetButtonPressed(false); + } + const bool bIsHoveredByMouse = (bAllowMouseHoverVisual && bIsInActiveTab && HoveredItem.Get() == Item && Item->IsButtonHovered()); + const bool bIsFocusedTarget = bShowNavVisual ? (Item == FocusedItem) : bIsHoveredByMouse; + Item->SetGamepadFocused(bIsFocusedTarget, bShowNavVisual || bIsHoveredByMouse); + } + } + + if (FocusedItem && bScrollIntoView && bShowNavVisual) + { + for (UPanelWidget* Parent = FocusedItem->GetParent(); Parent != nullptr; Parent = Parent->GetParent()) + { + if (UScrollBox* ScrollBox = Cast(Parent)) + { + ScrollBox->ScrollWidgetIntoView(FocusedItem, true, EDescendantScrollDestination::IntoView); + break; + } + } + } + + if (BackButton && bBackStyleCached) + { + const bool bBackFocused = bShowNavVisual && (FocusedItemIndex == -2); + BackButton->SetRenderTransformPivot(FVector2D(0.5f, 0.5f)); + if (bBackFocused) + { + const bool bPressed = bBackButtonPressed || BackButton->IsPressed(); + FSlateBrush HighlightBrush; + HighlightBrush.DrawAs = ESlateBrushDrawType::RoundedBox; + HighlightBrush.TintColor = FSlateColor(bPressed + ? FLinearColor(1.0f, 0.35f, 0.0f, 0.68f) + : FLinearColor(1.0f, 0.45f, 0.0f, 0.48f)); + HighlightBrush.OutlineSettings.CornerRadii = FVector4(10.0f, 10.0f, 10.0f, 10.0f); + HighlightBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; + HighlightBrush.OutlineSettings.Color = FSlateColor(FLinearColor(1.0f, 0.9f, 0.0f, 1.0f)); + HighlightBrush.OutlineSettings.Width = 6.0f; + + FButtonStyle FocusedStyle = OriginalBackButtonStyle; + FocusedStyle.SetNormal(HighlightBrush); + FocusedStyle.SetHovered(HighlightBrush); + FocusedStyle.SetPressed(HighlightBrush); + BackButton->SetStyle(FocusedStyle); + BackButton->SetBackgroundColor(FLinearColor::White); + BackButton->SetRenderScale(FVector2D(bPressed ? 0.88f : 1.12f, bPressed ? 0.88f : 1.12f)); + } + else + { + BackButton->SetStyle(OriginalBackButtonStyle); + BackButton->SetBackgroundColor(OriginalBackButtonBgColor); + BackButton->SetRenderScale(FVector2D(1.0f, 1.0f)); + } + } + + const bool bTabBarFocused = bShowNavVisual && (FocusedItemIndex == -1); + for (int32 i = 0; i < CheckBoxes.Num(); ++i) + { + UCheckBox* CB = CheckBoxes[i]; + UBorder* HighlightBorder = TabHighlightBorders.IsValidIndex(i) ? TabHighlightBorders[i].Get() : nullptr; + if (!CB) + { + continue; + } + UWidget* TabScaleTarget = CB->GetParent() + ? static_cast(CB->GetParent()) + : static_cast(CB); + TabScaleTarget->SetRenderTransformPivot(FVector2D(0.5f, 0.5f)); + if (i == ActiveTabIndex) + { + if (HighlightBorder) + { + FSlateBrush OverlayBrush; + OverlayBrush.DrawAs = ESlateBrushDrawType::RoundedBox; + OverlayBrush.ImageSize = CB->GetWidgetStyle().CheckedImage.ImageSize; + OverlayBrush.TintColor = FSlateColor(FLinearColor(1.0f, 0.45f, 0.0f, 0.48f)); + OverlayBrush.OutlineSettings.CornerRadii = FVector4(8.0f, 8.0f, 8.0f, 8.0f); + OverlayBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; + OverlayBrush.OutlineSettings.Color = FSlateColor(bTabBarFocused + ? FLinearColor(1.0f, 0.9f, 0.0f, 1.0f) + : FLinearColor::Transparent); + OverlayBrush.OutlineSettings.Width = bTabBarFocused ? 6.0f : 0.0f; + HighlightBorder->SetBrush(OverlayBrush); + HighlightBorder->SetBrushColor(FLinearColor::White); + HighlightBorder->SetVisibility(ESlateVisibility::HitTestInvisible); + } + const float TargetTabScale = bTabBarFocused ? 1.15f : 1.0f; + TabScaleTarget->SetRenderScale(FVector2D(TargetTabScale, TargetTabScale)); + } + else + { + if (HighlightBorder) + { + HighlightBorder->SetVisibility(ESlateVisibility::Collapsed); + } + TabScaleTarget->SetRenderScale(FVector2D(1.0f, 1.0f)); + } + } +} + +bool UStoreWidget::HandleGamepadKey(const FKey& Key, bool bIsPressed) +{ + if (!bIsPressed) + { + if (Key == EKeys::Gamepad_FaceButton_Bottom) + { + if (bBackButtonPressed) + { + bBackButtonPressed = false; + RefreshGamepadFocus(false); + if (FocusedItemIndex == -2) + { + OnBackButtonClicked(); + } + return true; + } + + USelectableItem* PreviouslyPressed = GamepadPressedItem.Get(); + GamepadPressedItem.Reset(); + + TArray ActiveItems; + if (ContentSwitcher) + { + GatherSelectableItems(ContentSwitcher->GetActiveWidget(), ActiveItems, true); + } + if (PreviouslyPressed && FocusedItemIndex >= 0 && FocusedItemIndex < ActiveItems.Num() && + ActiveItems[FocusedItemIndex] == PreviouslyPressed) + { + PreviouslyPressed->SetButtonPressed(false); + PreviouslyPressed->OnSelectionButtonClicked(); + } + else if (PreviouslyPressed) + { + PreviouslyPressed->SetButtonPressed(false); + } + return true; + } + return false; + } + + if (Key == EKeys::Gamepad_FaceButton_Right) + { + CancelPendingPress(); + OnBackButtonClicked(); + return true; + } + if (Key == EKeys::Gamepad_LeftShoulder) + { + SelectTabByIndex(ActiveTabIndex - 1); + return true; + } + if (Key == EKeys::Gamepad_RightShoulder) + { + SelectTabByIndex(ActiveTabIndex + 1); + return true; + } + + TArray ActiveItems; + if (ContentSwitcher) + { + GatherSelectableItems(ContentSwitcher->GetActiveWidget(), ActiveItems, true); + } + + // If opened via touch/mouse with navigation focus hidden, reveal focus on the first navigation/confirm press + if (!IsNavigationVisualActive()) + { + if (Key == EKeys::Gamepad_DPad_Left || Key == EKeys::Gamepad_DPad_Right || + Key == EKeys::Gamepad_DPad_Up || Key == EKeys::Gamepad_DPad_Down || + Key == EKeys::Gamepad_FaceButton_Bottom) + { + CancelPendingPress(); + if (Key == EKeys::Gamepad_DPad_Up || ActiveItems.Num() == 0) + { + FocusedItemIndex = -1; + } + else if (FocusedItemIndex < 0) + { + FocusedItemIndex = 0; + } + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->SetKeyNavigationActive(true); + } + RefreshGamepadFocus(true); + return true; + } + } + + if (Key == EKeys::Gamepad_DPad_Left) + { + CancelPendingPress(); + if (FocusedItemIndex == -2) + { + RefreshGamepadFocus(false); + } + else if (FocusedItemIndex == -1) + { + SelectTabByIndex(ActiveTabIndex - 1); + } + else if (ActiveItems.Num() > 1) + { + FocusedItemIndex = (FocusedItemIndex + ActiveItems.Num() - 1) % ActiveItems.Num(); + RefreshGamepadFocus(); + } + else + { + RefreshGamepadFocus(); + } + return true; + } + if (Key == EKeys::Gamepad_DPad_Right) + { + CancelPendingPress(); + if (FocusedItemIndex == -2) + { + RefreshGamepadFocus(false); + } + else if (FocusedItemIndex == -1) + { + SelectTabByIndex(ActiveTabIndex + 1); + } + else if (ActiveItems.Num() > 1) + { + FocusedItemIndex = (FocusedItemIndex + 1) % ActiveItems.Num(); + RefreshGamepadFocus(); + } + else + { + RefreshGamepadFocus(); + } + return true; + } + if (Key == EKeys::Gamepad_DPad_Up) + { + CancelPendingPress(); + if (FocusedItemIndex >= 0) + { + FocusedItemIndex = -1; + } + else if (FocusedItemIndex == -1 && BackButton) + { + FocusedItemIndex = -2; + } + RefreshGamepadFocus(false); + return true; + } + if (Key == EKeys::Gamepad_DPad_Down) + { + CancelPendingPress(); + if (FocusedItemIndex == -2) + { + FocusedItemIndex = -1; + } + else if (FocusedItemIndex == -1 && ActiveItems.Num() > 0) + { + FocusedItemIndex = 0; + } + RefreshGamepadFocus(); + return true; + } + if (Key == EKeys::Gamepad_FaceButton_Bottom) + { + if (FocusedItemIndex == -2 && BackButton) + { + bBackButtonPressed = true; + RefreshGamepadFocus(false); + } + else if (FocusedItemIndex >= 0 && FocusedItemIndex < ActiveItems.Num()) + { + GamepadPressedItem = ActiveItems[FocusedItemIndex]; + GamepadPressedItem->SetButtonPressed(true); + } + else if (FocusedItemIndex == -1 && ActiveItems.Num() > 0) + { + GamepadPressedItem.Reset(); + FocusedItemIndex = 0; + RefreshGamepadFocus(); + } + return true; + } + + return false; } void UStoreWidget::OnFuelBoxStateChanged(bool bIsChecked) diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Actors/TrivialKartHUD.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Actors/TrivialKartHUD.h index c327f1c9..b61d43a0 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Actors/TrivialKartHUD.h +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Actors/TrivialKartHUD.h @@ -19,8 +19,10 @@ #include "CoreMinimal.h" #include "GameFramework/HUD.h" +#include "InputCoreTypes.h" #include "TrivialKartHUD.generated.h" +class UTexture2D; DECLARE_LOG_CATEGORY_EXTERN(LogTemplateHUD, Log, All); @@ -34,6 +36,7 @@ enum class EWidgetType : uint8 PGS, Store }; + /** * */ @@ -47,6 +50,9 @@ class TRIVIALKART_UNREAL_API ATrivialKartHUD : public AHUD UPROPERTY() TMap> ActiveWidgets; + + UPROPERTY(Transient) + TObjectPtr CachedTouchHandTexture; public: virtual void BeginPlay() override; @@ -56,6 +62,27 @@ class TRIVIALKART_UNREAL_API ATrivialKartHUD : public AHUD void RemoveWidgetFromScreen(const EWidgetType WidgetType); UUserWidget* GetWidgetOfType(const EWidgetType WidgetType); - - + + bool HandleGamepadKey(const FKey& Key, bool bIsPressed = true, bool bIsRepeat = false); + bool IsSubMenuOpen() const; + bool IsUIBlockingInput() const; + bool IsStickNavigationEnabled() const; + void SyncGameplayInputContext() const; + + void ClearPlayBoardMenuFocus(); + void NotifyViewportPointerDown(const FVector2D& ScreenSpacePosition); + void CancelPendingPresses(); + void RefreshActiveSubMenu(); + + UTexture2D* GetOrCreateTouchHandTexture(); + +private: + static bool IsSubMenuWidgetType(EWidgetType WidgetType); + + template + T* GetActiveWidget(const EWidgetType WidgetType) const + { + const TWeakObjectPtr* Ptr = ActiveWidgets.Find(WidgetType); + return Ptr ? Cast(Ptr->Get()) : nullptr; + } }; diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Controllers/TrivialKartGamepadInputProcessor.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Controllers/TrivialKartGamepadInputProcessor.h new file mode 100644 index 00000000..5074e991 --- /dev/null +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Controllers/TrivialKartGamepadInputProcessor.h @@ -0,0 +1,74 @@ +/* +* Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#pragma once + +#include "CoreMinimal.h" +#include "Framework/Application/IInputProcessor.h" +#include "InputCoreTypes.h" +#include "UObject/WeakObjectPtr.h" + +class ATrivialKartPlayerController; + +enum class ETrivialKartStickDir : uint8 +{ + None, + Up, + Down, + Left, + Right +}; + +class TRIVIALKART_UNREAL_API FTrivialKartGamepadInputProcessor : public IInputProcessor +{ +public: + explicit FTrivialKartGamepadInputProcessor(ATrivialKartPlayerController* InOwner); + virtual ~FTrivialKartGamepadInputProcessor() override; + + virtual void Tick(const float DeltaTime, FSlateApplication& SlateApp, TSharedRef Cursor) override; + virtual bool HandleKeyDownEvent(FSlateApplication& SlateApp, const FKeyEvent& InKeyEvent) override; + virtual bool HandleKeyUpEvent(FSlateApplication& SlateApp, const FKeyEvent& InKeyEvent) override; + virtual bool HandleAnalogInputEvent(FSlateApplication& SlateApp, const FAnalogInputEvent& InAnalogInputEvent) override; + virtual bool HandleMouseButtonDownEvent(FSlateApplication& SlateApp, const FPointerEvent& MouseEvent) override; + virtual bool HandleMouseButtonUpEvent(FSlateApplication& SlateApp, const FPointerEvent& MouseEvent) override; + virtual bool HandleMouseMoveEvent(FSlateApplication& SlateApp, const FPointerEvent& MouseEvent) override; + + void ResetState(); + void ResetAnalogState(); + void LatchStickUntilNeutral(); + +private: + bool ProcessKeyEvent(const FKeyEvent& InKeyEvent, bool bIsPressed); + ETrivialKartStickDir ComputeDesiredStickDir() const; + static FKey StickDirToKey(ETrivialKartStickDir Dir); + void OnApplicationActivationChanged(const bool bIsActive); + + TWeakObjectPtr OwnerController; + FDelegateHandle AppActivationHandle; + + TSet ConsumedPressedKeys; + TSet HeldPhysicalKeys; + TSet LatchedRepeatKeys; + FVector2D AccumulatedMouseDelta = FVector2D::ZeroVector; + double LastGamepadActivityTimeSeconds = -100.0; + + float CachedLeftX = 0.0f; + float CachedLeftY = 0.0f; + float CachedLeftTrigger = 0.0f; + float CachedRightTrigger = 0.0f; + ETrivialKartStickDir ActiveStickDir = ETrivialKartStickDir::None; + float StickRepeatRemaining = 0.0f; + bool bLatchUntilNeutral = false; +}; diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Controllers/TrivialKartPlayerController.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Controllers/TrivialKartPlayerController.h index 6d011734..0eafaab5 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Controllers/TrivialKartPlayerController.h +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Controllers/TrivialKartPlayerController.h @@ -15,11 +15,46 @@ */ #pragma once +#include "Containers/Ticker.h" #include "CoreMinimal.h" #include "GameFramework/PlayerController.h" +#include "InputCoreTypes.h" +#include "InputModifiers.h" #include "TrivialKartPlayerController.generated.h" +class FTrivialKartGamepadInputProcessor; +class UInputAction; class UInputMappingContext; + +enum class ETrivialKartInputMode : uint8 +{ + Touch, + KeyboardMouse, + Gamepad +}; + +DECLARE_MULTICAST_DELEGATE_OneParam(FInputModeUpdated, ETrivialKartInputMode); + +/** + * Clamps trigger axis input so negative HID resting values (-1.0f) and + * uncalibrated Android DualSense resting values (+0.50f) do not actuate driving. + */ +UCLASS() +class TRIVIALKART_UNREAL_API UTrivialKartPositiveTriggerModifier : public UInputModifier +{ + GENERATED_BODY() + +public: + UPROPERTY(EditAnywhere, Category = "Settings") + float ActiveThreshold = 0.65f; + +protected: + virtual FInputActionValue ModifyRaw_Implementation( + const UEnhancedPlayerInput* PlayerInput, + FInputActionValue CurrentValue, + float DeltaTime) override; +}; + /** * */ @@ -30,9 +65,75 @@ class TRIVIALKART_UNREAL_API ATrivialKartPlayerController : public APlayerContro UPROPERTY(EditAnywhere, Category ="Input|Input Mappings") TObjectPtr DefaultMappingContext; + + UPROPERTY(EditAnywhere, Category ="Input|Input Mappings") + TObjectPtr UIMappingContext; + + UPROPERTY(Transient) + TObjectPtr RuntimeGameplayMappingContext; + + TSharedPtr GamepadInputProcessor; + FDelegateHandle DeviceConnectionChangeHandle; + FTSTicker::FDelegateHandle DeviceCheckTickerHandle; + FTSTicker::FDelegateHandle PeriodicDevicePollHandle; + +#if PLATFORM_ANDROID + ETrivialKartInputMode ActiveInputMode = ETrivialKartInputMode::Touch; +#else + ETrivialKartInputMode ActiveInputMode = ETrivialKartInputMode::KeyboardMouse; +#endif + ETrivialKartInputMode PreviousNonGamepadMode = ActiveInputMode; + bool bGameplayInputEnabled = true; + bool bKeyNavigationActive = false; + bool bWasGamepadAttached = false; + double LastNonGamepadInputTimeSeconds = -100.0; public: ATrivialKartPlayerController(); + virtual void BeginPlay() override; + virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; virtual void SetupInputComponent() override; + + bool HandleGamepadKey(const FKey& InKey, bool bIsPressed = true, bool bIsRepeat = false, bool bIsShiftDown = false); + bool HandleUICancelKey(bool bIsPressed); + + bool IsSubMenuOpen() const; + bool IsUIBlockingInput() const; + bool IsStickNavigationEnabled() const; + bool IsGamepadAttached() const { return bWasGamepadAttached; } + void SetGameplayInputEnabled(bool bEnabled); + + void SetActiveInputMode(ETrivialKartInputMode NewMode); + ETrivialKartInputMode GetActiveInputMode() const { return ActiveInputMode; } + + void NotifyExplicitDeviceInput(ETrivialKartInputMode DetectedMode); + void NotifyPointerDeviceInput(ETrivialKartInputMode PointerMode); + void SetKeyNavigationActive(bool bActive); + bool IsKeyNavigationActive() const { return ActiveInputMode == ETrivialKartInputMode::Gamepad || bKeyNavigationActive; } + + void ClearPlayBoardMenuFocus(); + void NotifyViewportPointerDown(const FVector2D& ScreenSpacePosition); + void CancelPendingPresses(); + void LatchStickUntilNeutral(); + void RestoreFocusToGameViewport(); + + int32 GetLocalPlayerUserIndex() const; + bool ShouldAcceptInputFromUser(int32 EventUserIndex, bool bIsGamepadEvent) const; + bool IsGameViewportFocused() const; + bool IsScreenPositionInGameViewport(const FVector2D& ScreenSpacePosition) const; + + FInputModeUpdated OnInputModeUpdated; + +private: + UInputMappingContext* GetOrCreateGameplayMappingContext(); + static FKey ResolveCanonicalUIKey(const UInputAction* Action, const TArray& UIMappings); + static FKey ResolveFallbackUIKey(const FKey& InKey, bool bIsShiftDown); + static bool IsDirectionalUIKey(const FKey& Key); + static bool QueryAnyGamepadAttached(); + void RemapAllDevicesToPrimaryUser() const; + void SyncGamepadAttachmentState(); + void OnInputDeviceConnectionChange(EInputDeviceConnectionState NewConnectionState, FPlatformUserId PlatformUserId, FInputDeviceId InputDeviceId); + bool EvaluateDeferredDeviceConnectionState(float DeltaTime); + bool PollDeviceConnectionState(float DeltaTime); }; diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/GarageWidget.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/GarageWidget.h index b880011d..1c19328d 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/GarageWidget.h +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/GarageWidget.h @@ -18,11 +18,17 @@ #include "CoreMinimal.h" #include "Blueprint/UserWidget.h" +#include "Controllers/TrivialKartPlayerController.h" +#include "InputCoreTypes.h" +#include "Styling/SlateTypes.h" #include "GarageWidget.generated.h" +class UBorder; +class UButton; class UWidgetSwitcher; class UCheckBox; -class UButton; +class USelectableItem; + /** * */ @@ -42,18 +48,50 @@ class TRIVIALKART_UNREAL_API UGarageWidget : public UUserWidget UPROPERTY(meta=(BindWidget)) TObjectPtr ContentSwitcher; - + protected: UPROPERTY() TArray CheckBoxes; + + UPROPERTY(Transient) + TArray> TabHighlightBorders; + + TWeakObjectPtr GamepadPressedItem; + TWeakObjectPtr HoveredItem; + + int32 ActiveTabIndex = 0; + int32 FocusedItemIndex = 0; + FButtonStyle OriginalBackButtonStyle; + FLinearColor OriginalBackButtonBgColor = FLinearColor::White; + bool bBackStyleCached = false; + bool bBackButtonPressed = false; + public: virtual void NativeConstruct() override; virtual void NativeDestruct() override; + + bool HandleGamepadKey(const FKey& Key, bool bIsPressed = true); + void RefreshGamepadFocus(bool bScrollIntoView = true); + void RefreshOwnershipAndFocus(bool bScrollIntoView = false); + void CancelPendingPress(); private: UFUNCTION() void OnBackButtonClicked(); + UFUNCTION() + void OnBackButtonReleased(); void SetCheckBoxState(bool bIsChecked, UCheckBox* CheckBox, int ActiveWidgetIndex); + void SelectTabByIndex(int32 NewTabIndex); + void RefreshAllItemsOwnership() const; + void GatherSelectableItems(UWidget* RootWidget, TArray& OutItems, bool bOnlySelectable) const; + int32 FindActiveCarItemIndex() const; + void OnSelectableItemInteracted(USelectableItem* InteractedItem); + void OnSelectableItemUnhovered(USelectableItem* UnhoveredItem); + void OnSelectableItemClicked(USelectableItem* ClickedItem); + void OnInputModeChanged(ETrivialKartInputMode NewInputMode); + bool IsNavigationVisualActive() const; + void RestoreViewportFocus() const; + UFUNCTION() void OnKartBoxStateChanged(bool bIsChecked); UFUNCTION() diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/PGSWidget.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/PGSWidget.h index 500a3ed5..eef75e68 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/PGSWidget.h +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/PGSWidget.h @@ -13,16 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #pragma once #include "CoreMinimal.h" #include "Blueprint/UserWidget.h" -#include "Components/TextBlock.h" +#include "Controllers/TrivialKartPlayerController.h" +#include "InputCoreTypes.h" +#include "Styling/SlateTypes.h" #include "PGSWidget.generated.h" -class UVerticalBox; +class UBorder; class UPGSLayoutText; class UScrollBox; +class UVerticalBox; class UWidgetSwitcher; class UCheckBox; class UButton; @@ -64,14 +68,36 @@ class TRIVIALKART_UNREAL_API UPGSWidget : public UUserWidget protected: UPROPERTY() TArray CheckBoxes; + + UPROPERTY(Transient) + TArray> TabHighlightBorders; + + int32 ActiveTabIndex = 0; + bool bBackButtonFocused = false; + bool bBackButtonPressed = false; + FButtonStyle OriginalBackButtonStyle; + FLinearColor OriginalBackButtonBgColor = FLinearColor::White; + bool bBackStyleCached = false; + public: virtual void NativeConstruct() override; virtual void NativeDestruct() override; + + bool HandleGamepadKey(const FKey& Key, bool bIsPressed = true); + void CancelPendingPress(); private: UFUNCTION() void OnBackButtonClicked(); + UFUNCTION() + void OnBackButtonReleased(); void SetCheckBoxState(bool bIsChecked, UCheckBox* CheckBox, int ActiveWidgetIndex); + void SelectTabByIndex(int32 NewTabIndex); + void UpdateTabFocusVisuals(); + void OnInputModeChanged(ETrivialKartInputMode NewInputMode); + bool IsNavigationVisualActive() const; + void RestoreViewportFocus() const; + UFUNCTION() void OnAuthCheckBoxStateChanged(bool bIsChecked); UFUNCTION() diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/PlayBoardWidget.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/PlayBoardWidget.h index 6bdc11cf..26986c03 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/PlayBoardWidget.h +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/PlayBoardWidget.h @@ -14,16 +14,22 @@ * limitations under the License. */ - #pragma once #include "CoreMinimal.h" #include "Blueprint/UserWidget.h" +#include "Controllers/TrivialKartPlayerController.h" +#include "InputCoreTypes.h" +#include "Misc/Optional.h" +#include "Styling/SlateTypes.h" #include "PlayBoardWidget.generated.h" +class UBorder; class UProgressBar; +class USizeBox; class UTextBlock; class UButton; + /** * */ @@ -34,28 +40,79 @@ class TRIVIALKART_UNREAL_API UPlayBoardWidget : public UUserWidget UPROPERTY(meta=(BindWidget)) TObjectPtr GarageButton; + UPROPERTY(meta=(BindWidget)) TObjectPtr PGSButton; + UPROPERTY(meta=(BindWidget)) TObjectPtr StoreButton; + UPROPERTY(meta=(BindWidget)) TObjectPtr DistanceText; + UPROPERTY(meta=(BindWidget)) TObjectPtr CoinText; + UPROPERTY(meta=(BindWidget)) TObjectPtr FuelBar; + TWeakObjectPtr InputGuideBorder; + TWeakObjectPtr InputGuideText; + TWeakObjectPtr TouchDrivePadSizeBox; + TWeakObjectPtr TouchDrivePadBorder; + + int32 FocusedButtonIndex = -1; + int32 PressedButtonIndex = -1; + bool bFocusedByHover = false; + TOptional LastRenderedGuideMode; + FButtonStyle OriginalButtonStyles[3]; + FLinearColor OriginalBackgroundColors[3]; + bool bStylesCached = false; + public: + virtual TSharedRef RebuildWidget() override; virtual void NativeConstruct() override; virtual void NativeDestruct() override; + + bool HandleGamepadKey(const FKey& Key, bool bIsPressed = true, bool bIsRepeat = false); + bool HasMenuFocus() const { return FocusedButtonIndex >= 0; } + bool HasBlockingMenuFocus() const { return FocusedButtonIndex >= 0 && !bFocusedByHover; } + void ClearMenuFocus(bool bOnlyIfNotHovered = false); + void CancelPendingPress(); + void OnViewportPointerDown(const FVector2D& ScreenSpacePosition); + void UpdateInputGuideText(ETrivialKartInputMode InputMode); private: + void EnsureInputGuideWidget(); + bool IsAnyMenuButtonHovered() const; + bool IsPointOverAnyMenuButton(const FVector2D& ScreenSpacePosition) const; + void SetHoverFocus(int32 NewButtonIndex); + void SetKeyboardOrGamepadFocus(int32 NewButtonIndex); + UFUNCTION() void OnGarageButtonClicked(); UFUNCTION() void OnPGSButtonClicked(); UFUNCTION() void OnStoreButtonClicked(); + + UFUNCTION() + void OnGarageButtonHovered(); + UFUNCTION() + void OnPGSButtonHovered(); + UFUNCTION() + void OnStoreButtonHovered(); + UFUNCTION() + void OnMenuButtonUnhovered(); + + UFUNCTION() + void OnGarageButtonPressed(); + UFUNCTION() + void OnPGSButtonPressed(); + UFUNCTION() + void OnStoreButtonPressed(); + UFUNCTION() + void OnMenuButtonReleased(); UFUNCTION() void UpdateFuelBar(const float FuelBarPercentage) const; @@ -63,4 +120,6 @@ class TRIVIALKART_UNREAL_API UPlayBoardWidget : public UUserWidget void UpdateDistanceText(const float Distance) const; UFUNCTION() void UpdateCoinText(const int Quantity) const; + + void UpdateButtonFocusVisuals(); }; diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/SelectableItem.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/SelectableItem.h index 393dd662..a82387d0 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/SelectableItem.h +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/SelectableItem.h @@ -27,7 +27,7 @@ enum class ESelectableOperationType : uint8 None, InAppPurchase, CoinPurchase, - ObjectSelection, + ObjectSelection }; UENUM() @@ -36,10 +36,12 @@ enum class EPurchaseObject : uint8 None, Fuel, Car, - Coin + Coin, + Subscription }; class UButtonWidgetStyle; class UButton; +class UBorder; class SButton; /** * @@ -56,25 +58,36 @@ class TRIVIALKART_UNREAL_API USelectableItem : public UUserWidget FButtonStyle SelectionButtonStyle; UPROPERTY(EditAnywhere) - ESelectableOperationType SelectionOperationType; + ESelectableOperationType SelectionOperationType = ESelectableOperationType::None; + + UPROPERTY(EditAnywhere) + EPurchaseObject PurchaseObject = EPurchaseObject::None; UPROPERTY(EditAnywhere, meta = (EditCondition = "SelectionOperationType == ESelectableOperationType::InAppPurchase", EditConditionHides)) FString PurchaseID; UPROPERTY(EditAnywhere, meta = (EditCondition = "SelectionOperationType == ESelectableOperationType::InAppPurchase", EditConditionHides)) - int PurchaseQuantity; + bool bIsConsumable = true; UPROPERTY(EditAnywhere, meta = (EditCondition = "SelectionOperationType == ESelectableOperationType::InAppPurchase", EditConditionHides)) - bool bIsConsumable; + int PurchaseQuantity = 1; UPROPERTY(EditAnywhere, meta = (EditCondition = "SelectionOperationType == ESelectableOperationType::CoinPurchase", EditConditionHides)) - int CoinQuantity; - - UPROPERTY(EditAnywhere) - EPurchaseObject PurchaseObject; + int CoinQuantity = 10; UPROPERTY(EditAnywhere, meta = (EditCondition = "PurchaseObject == EPurchaseObject::Car", EditConditionHides)) FString CarType; + + UPROPERTY(Transient) + TObjectPtr FocusHighlightBorder; + + bool bIsGamepadFocused = false; + bool bShowFocusVisual = false; + bool bIsButtonPressed = false; + + void EnsureOverlayHitTestAndBorder(); + UWidget* GetVisualScaleTarget() const; + void UpdateHighlightVisuals(); public: virtual void NativePreConstruct() override; @@ -83,4 +96,31 @@ class TRIVIALKART_UNREAL_API USelectableItem : public UUserWidget UFUNCTION() void OnSelectionButtonClicked(); + + UFUNCTION() + void OnSelectionButtonHovered(); + + UFUNCTION() + void OnSelectionButtonUnhovered(); + + UFUNCTION() + void OnSelectionButtonPressed(); + + UFUNCTION() + void OnSelectionButtonReleased(); + + void SetButtonPressed(bool bInPressed); + + DECLARE_DELEGATE_OneParam(FOnSelectableItemInteracted, USelectableItem*); + FOnSelectableItemInteracted OnItemInteracted; + FOnSelectableItemInteracted OnItemUnhovered; + FOnSelectableItemInteracted OnItemClicked; + + void SetGamepadFocused(bool bInFocused, bool bInShowVisual = true); + bool IsGamepadFocused() const { return bIsGamepadFocused; } + bool IsButtonHovered() const; + bool IsItemSelectable() const; + void RefreshOwnershipState(); + EPurchaseObject GetPurchaseObject() const { return PurchaseObject; } + const FString& GetCarType() const { return CarType; } }; diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/StoreWidget.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/StoreWidget.h index 547c5ad4..a88f79fc 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/StoreWidget.h +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/StoreWidget.h @@ -13,15 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #pragma once #include "CoreMinimal.h" #include "Blueprint/UserWidget.h" +#include "Controllers/TrivialKartPlayerController.h" +#include "InputCoreTypes.h" +#include "Styling/SlateTypes.h" #include "StoreWidget.generated.h" +class UBorder; +class UButton; class UWidgetSwitcher; class UCheckBox; -class UButton; +class USelectableItem; + /** * */ @@ -51,14 +58,45 @@ class TRIVIALKART_UNREAL_API UStoreWidget : public UUserWidget protected: UPROPERTY() TArray CheckBoxes; + + UPROPERTY(Transient) + TArray> TabHighlightBorders; + + TWeakObjectPtr GamepadPressedItem; + TWeakObjectPtr HoveredItem; + + int32 ActiveTabIndex = 0; + int32 FocusedItemIndex = 0; + FButtonStyle OriginalBackButtonStyle; + FLinearColor OriginalBackButtonBgColor = FLinearColor::White; + bool bBackStyleCached = false; + bool bBackButtonPressed = false; + public: virtual void NativeConstruct() override; virtual void NativeDestruct() override; + + bool HandleGamepadKey(const FKey& Key, bool bIsPressed = true); + void RefreshGamepadFocus(bool bScrollIntoView = true); + void RefreshOwnershipAndFocus(bool bScrollIntoView = false); + void CancelPendingPress(); private: UFUNCTION() void OnBackButtonClicked(); + UFUNCTION() + void OnBackButtonReleased(); void SetCheckBoxState(bool bIsChecked, UCheckBox* CheckBox, int ActiveWidgetIndex); + void SelectTabByIndex(int32 NewTabIndex); + void RefreshAllItemsOwnership() const; + void GatherSelectableItems(UWidget* RootWidget, TArray& OutItems, bool bOnlySelectable) const; + void OnSelectableItemInteracted(USelectableItem* InteractedItem); + void OnSelectableItemUnhovered(USelectableItem* UnhoveredItem); + void OnSelectableItemClicked(USelectableItem* ClickedItem); + void OnInputModeChanged(ETrivialKartInputMode NewInputMode); + bool IsNavigationVisualActive() const; + void RestoreViewportFocus() const; + UFUNCTION() void OnFuelBoxStateChanged(bool bIsChecked); UFUNCTION() diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/TrivialKart_Unreal.Build.cs b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/TrivialKart_Unreal.Build.cs index 39ff4eec..e98cc3d3 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/TrivialKart_Unreal.Build.cs +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/TrivialKart_Unreal.Build.cs @@ -27,6 +27,7 @@ public TrivialKart_Unreal(ReadOnlyTargetRules Target) : base(Target) "Core", "CoreUObject", "Engine", + "ApplicationCore", "InputCore", "EnhancedInput", "Paper2D", diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_UnrealEditor.Target.cs b/trivialkart/trivialkart_unreal/Source/TrivialKart_UnrealEditor.Target.cs index eba0a3eb..2db84052 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_UnrealEditor.Target.cs +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_UnrealEditor.Target.cs @@ -23,8 +23,8 @@ public class TrivialKart_UnrealEditorTarget : TargetRules public TrivialKart_UnrealEditorTarget( TargetInfo Target) : base(Target) { Type = TargetType.Editor; - DefaultBuildSettings = BuildSettingsVersion.V6; - IncludeOrderVersion = EngineIncludeOrderVersion.Unreal5_7; + DefaultBuildSettings = BuildSettingsVersion.Latest; + IncludeOrderVersion = EngineIncludeOrderVersion.Latest; ExtraModuleNames.Add("TrivialKart_Unreal"); } } From 684a33ae6b9ab9f6a9e1c20a8f12626b8d48aa2b Mon Sep 17 00:00:00 2001 From: Meerae Choi Date: Wed, 18 Nov 2026 05:07:58 +0000 Subject: [PATCH 2/2] trivialkart_unreal: Address PR #126 review feedback and multi-controller polish - Extract UTrivialKartTabbedModalWidget and TrivialKartUIStyle to share modal navigation, tab switching, item focus caching, and rounded highlight styling across StoreWidget, GarageWidget, and PGSWidget. - Block gamepad, keyboard, and pointer input while the Loading overlay is active, restore initial BeginPlay Loading display with a cloud-sync timeout fallback, and refresh open submenus via RefreshActiveSubMenu() when cloud save operations finish. - Support both digital-only triggers (e.g. Nintendo Switch Pro / Joy-Con) and analog triggers (including Android DualSense +0.50 resting offset) per FInputDeviceId via UTrivialKartDriveInputModifier without dynamic mapping context rebuild lockouts, and guard against DualSense touchpad phantom Touch1. - Track per-device controller families (Xbox A, PlayStation X, Nintendo Switch B) for instant HUD prompt switching across simultaneously connected Bluetooth controllers, including multiple identical controllers and hotplug/disconnect. - Inset PlayBoard HUD button focus frames and SelectableItem card highlights so button labels stay centered and focus borders never clip on curved phone screen corners or ScrollBox bounds. --- trivialkart/trivialkart_unreal/.gitignore | 1 - .../Config/DefaultEngine.ini | 1 + trivialkart/trivialkart_unreal/README.md | 4 +- .../Private/Actors/TrivialKartHUD.cpp | 142 +- .../TrivialKartGamepadInputProcessor.cpp | 432 ++++- .../TrivialKartPlayerController.cpp | 1398 +++++++++++++++-- .../GameInstances/TrivialKartGameInstance.cpp | 183 ++- .../Private/Infos/TrivialKartPlayerState.cpp | 22 + .../Private/Widgets/GarageWidget.cpp | 647 +------- .../Private/Widgets/PGSWidget.cpp | 434 +---- .../Private/Widgets/PlayBoardWidget.cpp | 234 ++- .../Private/Widgets/SelectableItem.cpp | 32 +- .../Private/Widgets/StoreWidget.cpp | 628 +------- .../Widgets/TrivialKartTabbedModalWidget.cpp | 705 +++++++++ .../Public/Actors/TrivialKartHUD.h | 3 + .../TrivialKartGamepadInputProcessor.h | 66 +- .../Controllers/TrivialKartPlayerController.h | 99 +- .../GameInstances/TrivialKartGameInstance.h | 9 + .../Public/Infos/TrivialKartPlayerState.h | 1 + .../Public/Widgets/GarageWidget.h | 70 +- .../Public/Widgets/PGSWidget.h | 75 +- .../Public/Widgets/PlayBoardWidget.h | 11 +- .../Public/Widgets/SelectableItem.h | 2 - .../Public/Widgets/StoreWidget.h | 75 +- .../Widgets/TrivialKartTabbedModalWidget.h | 109 ++ .../Public/Widgets/TrivialKartUIStyle.h | 95 ++ .../TrivialKart_Unreal.Build.cs | 1 + 27 files changed, 3205 insertions(+), 2274 deletions(-) create mode 100644 trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/TrivialKartTabbedModalWidget.cpp create mode 100644 trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/TrivialKartTabbedModalWidget.h create mode 100644 trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/TrivialKartUIStyle.h diff --git a/trivialkart/trivialkart_unreal/.gitignore b/trivialkart/trivialkart_unreal/.gitignore index 5e081af6..4c16cddb 100644 --- a/trivialkart/trivialkart_unreal/.gitignore +++ b/trivialkart/trivialkart_unreal/.gitignore @@ -52,7 +52,6 @@ Plugins/*/Binaries/* # Builds Build/* -Builds/* # Whitelist PakBlacklist-.txt files !Build/*/ diff --git a/trivialkart/trivialkart_unreal/Config/DefaultEngine.ini b/trivialkart/trivialkart_unreal/Config/DefaultEngine.ini index 11120c36..ac4ab05f 100644 --- a/trivialkart/trivialkart_unreal/Config/DefaultEngine.ini +++ b/trivialkart/trivialkart_unreal/Config/DefaultEngine.ini @@ -21,6 +21,7 @@ r.Mobile.ShadingPath=1 r.Mobile.AntiAliasing=2 r.Mobile.FloatPrecisionMode=0 r.Mobile.AllowDitheredLODTransition=False +r.Mobile.VirtualTextures=False r.DiscardUnusedQuality=False r.AllowOcclusionQueries=True r.MinScreenRadiusForLights=0.030000 diff --git a/trivialkart/trivialkart_unreal/README.md b/trivialkart/trivialkart_unreal/README.md index d09dacbc..00775bef 100644 --- a/trivialkart/trivialkart_unreal/README.md +++ b/trivialkart/trivialkart_unreal/README.md @@ -35,8 +35,8 @@ By default, Google Play features are simulated or disabled unless the Google Pla ## Overview -In TrivialKart, the player has a vehicle which they can drive by touching and holding on screen, holding a gamepad trigger / `A` / D-Pad Right / Left Stick Right, or holding `Spacebar` / clicking. -Navigate menus (`Garage`, `Play Games Services`, `Store`) using D-Pad or Left Stick, switch tabs with `LB` / `RB` (or `Tab` / `Shift+Tab`), confirm with `A` (`Enter`), and go back with `B` (`Esc` or Android Back). +In TrivialKart, the player has a vehicle which they can drive by touching and holding on screen, holding a gamepad trigger / primary face button (`A` on Xbox, `X` on PlayStation, `B` on Nintendo Switch) / D-Pad Right / Left Stick Right, or holding `Spacebar` / clicking. +Navigate menus (`Garage`, `Play Games Services`, `Store`) using D-Pad or Left Stick, switch tabs with `LB` / `RB` (`L1` / `R1`, `L` / `R`, or `Tab` / `Shift+Tab`), confirm with the bottom face button (`Enter`), and go back with the right face button (`Esc` or Android Back). Driving the car uses gas. When the car runs out of gas, to continue driving, more must be purchased using in-game currency. If the player runs out of in-game currency, they may buy more via in-app purchases. diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Actors/TrivialKartHUD.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Actors/TrivialKartHUD.cpp index 8fe226d8..7af8be2f 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Actors/TrivialKartHUD.cpp +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Actors/TrivialKartHUD.cpp @@ -19,17 +19,16 @@ #include "Controllers/TrivialKartPlayerController.h" #include "Engine/Texture2D.h" +#include "GameInstances/TrivialKartGameInstance.h" #include "TextureResource.h" -#include "Widgets/GarageWidget.h" -#include "Widgets/PGSWidget.h" #include "Widgets/PlayBoardWidget.h" -#include "Widgets/StoreWidget.h" +#include "Widgets/TrivialKartTabbedModalWidget.h" DEFINE_LOG_CATEGORY(LogTemplateHUD); namespace { - float DistToSegment2D(float Px, float Py, float Ax, float Ay, float Bx, float By) + float DistToSegmentSq2D(float Px, float Py, float Ax, float Ay, float Bx, float By) { const float Vx = Bx - Ax; const float Vy = By - Ay; @@ -38,21 +37,24 @@ namespace const float C1 = Wx * Vx + Wy * Vy; if (C1 <= 0.0f) { - return FMath::Sqrt(Wx * Wx + Wy * Wy); + return Wx * Wx + Wy * Wy; } const float C2 = Vx * Vx + Vy * Vy; if (C2 <= C1) { const float Dx = Px - Bx; const float Dy = Py - By; - return FMath::Sqrt(Dx * Dx + Dy * Dy); + return Dx * Dx + Dy * Dy; } const float T = C1 / C2; - const float ProjX = Ax + T * Vx; - const float ProjY = Ay + T * Vy; - const float Dx = Px - ProjX; - const float Dy = Py - ProjY; - return FMath::Sqrt(Dx * Dx + Dy * Dy); + const float Dx = Px - (Ax + T * Vx); + const float Dy = Py - (Ay + T * Vy); + return Dx * Dx + Dy * Dy; + } + + float SignedCapsuleDist2D(float Px, float Py, float Ax, float Ay, float Bx, float By, float Radius) + { + return FMath::Sqrt(DistToSegmentSq2D(Px, Py, Ax, Ay, Bx, By)) - Radius; } UTexture2D* BuildProceduralTouchHandTexture() @@ -80,25 +82,22 @@ namespace const float Px = static_cast(X) + 0.5f; const float Py = static_cast(Y) + 0.5f; - const float DIndex = DistToSegment2D(Px, Py, 44.0f, 26.0f, 44.0f, 58.0f) - 6.2f; - const float DMiddle = DistToSegment2D(Px, Py, 55.5f, 43.0f, 55.5f, 60.0f) - 5.4f; - const float DRing = DistToSegment2D(Px, Py, 66.0f, 47.0f, 66.0f, 62.0f) - 5.1f; - const float DPinky = DistToSegment2D(Px, Py, 75.5f, 52.0f, 74.0f, 66.0f) - 4.7f; - const float DThumb = DistToSegment2D(Px, Py, 28.0f, 54.0f, 42.0f, 68.0f) - 5.8f; - const float DPalmUpper = DistToSegment2D(Px, Py, 44.0f, 58.0f, 69.0f, 63.0f) - 12.5f; - const float DPalmLower = DistToSegment2D(Px, Py, 48.0f, 69.0f, 61.0f, 72.0f) - 14.5f; - - float HandDist = FMath::Min(DIndex, DMiddle); - HandDist = FMath::Min(HandDist, DRing); - HandDist = FMath::Min(HandDist, DPinky); - HandDist = FMath::Min(HandDist, DThumb); - HandDist = FMath::Min(HandDist, DPalmUpper); - HandDist = FMath::Min(HandDist, DPalmLower); - - const float DGroove1 = DistToSegment2D(Px, Py, 50.0f, 41.0f, 50.0f, 53.0f); - const float DGroove2 = DistToSegment2D(Px, Py, 61.0f, 45.0f, 61.0f, 55.0f); - const float DGroove3 = DistToSegment2D(Px, Py, 71.0f, 50.0f, 71.0f, 58.0f); - const float GrooveDist = FMath::Min(DGroove1, FMath::Min(DGroove2, DGroove3)); + float HandDist = SignedCapsuleDist2D(Px, Py, 44.0f, 26.0f, 44.0f, 58.0f, 6.2f); + HandDist = FMath::Min(HandDist, SignedCapsuleDist2D(Px, Py, 55.5f, 43.0f, 55.5f, 60.0f, 5.4f)); + HandDist = FMath::Min(HandDist, SignedCapsuleDist2D(Px, Py, 66.0f, 47.0f, 66.0f, 62.0f, 5.1f)); + HandDist = FMath::Min(HandDist, SignedCapsuleDist2D(Px, Py, 75.5f, 52.0f, 74.0f, 66.0f, 4.7f)); + HandDist = FMath::Min(HandDist, SignedCapsuleDist2D(Px, Py, 28.0f, 54.0f, 42.0f, 68.0f, 5.8f)); + HandDist = FMath::Min(HandDist, SignedCapsuleDist2D(Px, Py, 44.0f, 58.0f, 69.0f, 63.0f, 12.5f)); + HandDist = FMath::Min(HandDist, SignedCapsuleDist2D(Px, Py, 48.0f, 69.0f, 61.0f, 72.0f, 14.5f)); + + float GrooveDist = 100.0f; + if (HandDist < -1.0f) + { + const float DGrooveSq1 = DistToSegmentSq2D(Px, Py, 50.0f, 41.0f, 50.0f, 53.0f); + const float DGrooveSq2 = DistToSegmentSq2D(Px, Py, 61.0f, 45.0f, 61.0f, 55.0f); + const float DGrooveSq3 = DistToSegmentSq2D(Px, Py, 71.0f, 50.0f, 71.0f, 58.0f); + GrooveDist = FMath::Sqrt(FMath::Min(DGrooveSq1, FMath::Min(DGrooveSq2, DGrooveSq3))); + } const float TipDist = FVector2D::Distance(FVector2D(Px, Py), FVector2D(44.0f, 24.0f)); float RippleDist = 100.0f; @@ -154,6 +153,13 @@ bool ATrivialKartHUD::IsSubMenuWidgetType(EWidgetType WidgetType) void ATrivialKartHUD::BeginPlay() { Super::BeginPlay(); + if (const UTrivialKartGameInstance* Instance = Cast(GetGameInstance())) + { + if (Instance->IsCloudSyncInFlight()) + { + AddWidgetToScreen(EWidgetType::Loading, 10); + } + } AddWidgetToScreen(EWidgetType::PlayBoard); } @@ -185,6 +191,10 @@ void ATrivialKartHUD::AddWidgetToScreen(const EWidgetType WidgetType, int32 ZOrd const TWeakObjectPtr CurrentWidget = CreateWidget(GetOwningPlayerController(), WidgetTemplates[WidgetType]); if (CurrentWidget.IsValid()) { + if (WidgetType == EWidgetType::Loading) + { + CancelPendingPresses(); + } CurrentWidget->AddToViewport(ZOrder); ActiveWidgets.Emplace(WidgetType, CurrentWidget); SyncGameplayInputContext(); @@ -202,7 +212,14 @@ void ATrivialKartHUD::RemoveWidgetFromScreen(const EWidgetType WidgetType) const TWeakObjectPtr* ExistingPtr = ActiveWidgets.Find(WidgetType); if (!ExistingPtr) { - UE_LOG(LogTemplateHUD, Warning, TEXT("Widget is not on Screen")); + if (WidgetType == EWidgetType::Loading) + { + RefreshActiveSubMenu(); + } + else + { + UE_LOG(LogTemplateHUD, Warning, TEXT("Widget is not on Screen")); + } return; } if (UUserWidget* ExistingWidget = ExistingPtr->Get()) @@ -212,6 +229,11 @@ void ATrivialKartHUD::RemoveWidgetFromScreen(const EWidgetType WidgetType) ActiveWidgets.Remove(WidgetType); SyncGameplayInputContext(); + if (WidgetType == EWidgetType::Loading) + { + RefreshActiveSubMenu(); + } + if (ATrivialKartPlayerController* PlayerController = Cast(GetOwningPlayerController())) { PlayerController->LatchStickUntilNeutral(); @@ -228,19 +250,28 @@ UUserWidget* ATrivialKartHUD::GetWidgetOfType(const EWidgetType WidgetType) return nullptr; } -bool ATrivialKartHUD::HandleGamepadKey(const FKey& Key, bool bIsPressed, bool bIsRepeat) +UTrivialKartTabbedModalWidget* ATrivialKartHUD::GetActiveSubMenuWidget() const { - if (UStoreWidget* Store = GetActiveWidget(EWidgetType::Store)) + if (UTrivialKartTabbedModalWidget* Store = GetActiveWidget(EWidgetType::Store)) + { + return Store; + } + if (UTrivialKartTabbedModalWidget* Garage = GetActiveWidget(EWidgetType::Garage)) { - return Store->HandleGamepadKey(Key, bIsPressed); + return Garage; } - if (UGarageWidget* Garage = GetActiveWidget(EWidgetType::Garage)) + return GetActiveWidget(EWidgetType::PGS); +} + +bool ATrivialKartHUD::HandleGamepadKey(const FKey& Key, bool bIsPressed, bool bIsRepeat) +{ + if (IsLoadingOpen()) { - return Garage->HandleGamepadKey(Key, bIsPressed); + return bIsPressed; } - if (UPGSWidget* PGS = GetActiveWidget(EWidgetType::PGS)) + if (UTrivialKartTabbedModalWidget* SubMenu = GetActiveSubMenuWidget()) { - return PGS->HandleGamepadKey(Key, bIsPressed); + return SubMenu->HandleGamepadKey(Key, bIsPressed); } if (UPlayBoardWidget* PlayBoard = GetActiveWidget(EWidgetType::PlayBoard)) { @@ -249,16 +280,19 @@ bool ATrivialKartHUD::HandleGamepadKey(const FKey& Key, bool bIsPressed, bool bI return false; } +bool ATrivialKartHUD::IsLoadingOpen() const +{ + return GetActiveWidget(EWidgetType::Loading) != nullptr; +} + bool ATrivialKartHUD::IsSubMenuOpen() const { - return GetActiveWidget(EWidgetType::Store) != nullptr - || GetActiveWidget(EWidgetType::Garage) != nullptr - || GetActiveWidget(EWidgetType::PGS) != nullptr; + return GetActiveSubMenuWidget() != nullptr; } bool ATrivialKartHUD::IsUIBlockingInput() const { - if (IsSubMenuOpen()) + if (IsLoadingOpen() || IsSubMenuOpen()) { return true; } @@ -268,6 +302,10 @@ bool ATrivialKartHUD::IsUIBlockingInput() const bool ATrivialKartHUD::IsStickNavigationEnabled() const { + if (IsLoadingOpen()) + { + return false; + } if (IsSubMenuOpen()) { return true; @@ -307,17 +345,9 @@ void ATrivialKartHUD::NotifyViewportPointerDown(const FVector2D& ScreenSpacePosi void ATrivialKartHUD::CancelPendingPresses() { - if (UStoreWidget* Store = GetActiveWidget(EWidgetType::Store)) - { - Store->CancelPendingPress(); - } - if (UGarageWidget* Garage = GetActiveWidget(EWidgetType::Garage)) - { - Garage->CancelPendingPress(); - } - if (UPGSWidget* PGS = GetActiveWidget(EWidgetType::PGS)) + if (UTrivialKartTabbedModalWidget* SubMenu = GetActiveSubMenuWidget()) { - PGS->CancelPendingPress(); + SubMenu->CancelPendingPress(); } if (UPlayBoardWidget* PlayBoard = GetActiveWidget(EWidgetType::PlayBoard)) { @@ -327,13 +357,9 @@ void ATrivialKartHUD::CancelPendingPresses() void ATrivialKartHUD::RefreshActiveSubMenu() { - if (UStoreWidget* Store = GetActiveWidget(EWidgetType::Store)) - { - Store->RefreshOwnershipAndFocus(false); - } - if (UGarageWidget* Garage = GetActiveWidget(EWidgetType::Garage)) + if (UTrivialKartTabbedModalWidget* SubMenu = GetActiveSubMenuWidget()) { - Garage->RefreshOwnershipAndFocus(false); + SubMenu->RefreshOwnershipAndFocus(false); } } diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Controllers/TrivialKartGamepadInputProcessor.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Controllers/TrivialKartGamepadInputProcessor.cpp index 48519afc..2344c285 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Controllers/TrivialKartGamepadInputProcessor.cpp +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Controllers/TrivialKartGamepadInputProcessor.cpp @@ -51,6 +51,8 @@ namespace || Key == EKeys::Gamepad_DPad_Down || Key == EKeys::Gamepad_DPad_Left || Key == EKeys::Gamepad_DPad_Right + || Key == EKeys::Gamepad_LeftTrigger + || Key == EKeys::Gamepad_RightTrigger || Key == EKeys::Up || Key == EKeys::Down || Key == EKeys::Left @@ -60,20 +62,48 @@ namespace || Key == EKeys::Enter; } + bool IsExplicitGamepadPromptSwitchKey(const FKey& Key) + { + if (!Key.IsGamepadKey() || Key.IsAxis1D() || Key.IsAxis2D()) + { + return false; + } + // Ignore right-stick synthesized digital keys: TrivialKart does not use the right stick, + // and Android DualSense uncalibrated Z/RZ/RX/RY axes can synthesize right-stick events while idle. + if (Key == EKeys::Gamepad_RightStick_Up || + Key == EKeys::Gamepad_RightStick_Down || + Key == EKeys::Gamepad_RightStick_Left || + Key == EKeys::Gamepad_RightStick_Right || + Key == EKeys::Gamepad_RightThumbstick) + { + return false; + } + return true; + } + bool IsGamepadTriggerAxis(const FKey& Key) { return Key == EKeys::Gamepad_LeftTriggerAxis || Key == EKeys::Gamepad_RightTriggerAxis; } + bool TouchPosIsCornerPhantom(const FVector2D& Pos) + { + return Pos.X <= 1.0f && Pos.Y <= 1.0f; + } + bool IsGenuineKeyboardKey(const FKey& Key) { if (!Key.IsValid() || Key.IsGamepadKey() || Key.IsTouch() || Key.IsMouseButton() || Key.IsAxis1D() || Key.IsAxis2D()) { return false; } - const FString KeyName = Key.GetFName().ToString(); - if (KeyName.StartsWith(TEXT("Android_")) || KeyName.StartsWith(TEXT("Steam_")) || KeyName.StartsWith(TEXT("Gesture_"))) + TCHAR KeyName[NAME_SIZE]; + Key.GetFName().GetPlainNameString(KeyName); + if (FCString::Strnicmp(KeyName, TEXT("Android_"), 8) == 0 || + FCString::Strnicmp(KeyName, TEXT("Steam_"), 6) == 0 || + FCString::Strnicmp(KeyName, TEXT("Gesture_"), 8) == 0 || + FCString::Strnicmp(KeyName, TEXT("Touch"), 5) == 0) { return false; } @@ -102,10 +132,15 @@ FTrivialKartGamepadInputProcessor::~FTrivialKartGamepadInputProcessor() void FTrivialKartGamepadInputProcessor::ResetAnalogState() { - CachedLeftX = 0.0f; - CachedLeftY = 0.0f; - CachedLeftTrigger = 0.0f; - CachedRightTrigger = 0.0f; + for (TPair& Pair : DeviceStates) + { + Pair.Value.LeftX = 0.0f; + Pair.Value.LeftY = 0.0f; + Pair.Value.LeftTriggerAnalog = 0.0f; + Pair.Value.RightTriggerAnalog = 0.0f; + Pair.Value.bDigitalLeftTriggerHeld = false; + Pair.Value.bDigitalRightTriggerHeld = false; + } ActiveStickDir = ETrivialKartStickDir::None; StickRepeatRemaining = 0.0f; bLatchUntilNeutral = false; @@ -122,15 +157,102 @@ void FTrivialKartGamepadInputProcessor::ResetState() HeldPhysicalKeys.Empty(); LatchedRepeatKeys.Empty(); AccumulatedMouseDelta = FVector2D::ZeroVector; + bIsPrimaryTouchHeld = false; + bIsPrimaryMouseHeld = false; ResetAnalogState(); } +void FTrivialKartGamepadInputProcessor::ResetDeviceCapabilities() +{ + DeviceStates.Empty(); +} + +void FTrivialKartGamepadInputProcessor::RemoveDeviceState(FInputDeviceId DeviceId) +{ + DeviceStates.Remove(DeviceId); + for (auto It = ConsumedPressedKeys.CreateIterator(); It; ++It) + { + if (It->DeviceId == DeviceId) + { + It.RemoveCurrent(); + } + } + for (auto It = HeldPhysicalKeys.CreateIterator(); It; ++It) + { + if (It->DeviceId == DeviceId) + { + It.RemoveCurrent(); + } + } + for (auto It = LatchedRepeatKeys.CreateIterator(); It; ++It) + { + if (It->DeviceId == DeviceId) + { + It.RemoveCurrent(); + } + } +} + +float FTrivialKartGamepadInputProcessor::GetMaxTriggerAnalog(bool bRightTrigger) const +{ + float MaxValue = 0.0f; + for (const TPair& Pair : DeviceStates) + { + const float Candidate = bRightTrigger ? Pair.Value.RightTriggerAnalog : Pair.Value.LeftTriggerAnalog; + MaxValue = FMath::Max(MaxValue, Candidate); + } + return MaxValue; +} + +bool FTrivialKartGamepadInputProcessor::IsDigitalTriggerHeld(bool bRightTrigger) const +{ + for (const TPair& Pair : DeviceStates) + { + const bool bHasAnalog = bRightTrigger ? Pair.Value.bHasRightTriggerAnalog : Pair.Value.bHasLeftTriggerAnalog; + const bool bDigitalHeld = bRightTrigger ? Pair.Value.bDigitalRightTriggerHeld : Pair.Value.bDigitalLeftTriggerHeld; + if (!bHasAnalog && bDigitalHeld) + { + return true; + } + } + return false; +} + +ETrivialKartDeviceTriggerSignature FTrivialKartGamepadInputProcessor::GetDeviceTriggerSignature(FInputDeviceId DeviceId) const +{ + if (const FTrivialKartDeviceInputState* Found = DeviceStates.Find(DeviceId)) + { + return Found->TriggerSignature; + } + return ETrivialKartDeviceTriggerSignature::Unknown; +} + +void FTrivialKartGamepadInputProcessor::GetDominantStickAxes(float& OutLeftX, float& OutLeftY) const +{ + OutLeftX = 0.0f; + OutLeftY = 0.0f; + float BestMagSq = 0.0f; + for (const TPair& Pair : DeviceStates) + { + const float MagSq = Pair.Value.LeftX * Pair.Value.LeftX + Pair.Value.LeftY * Pair.Value.LeftY; + if (MagSq > BestMagSq) + { + BestMagSq = MagSq; + OutLeftX = Pair.Value.LeftX; + OutLeftY = Pair.Value.LeftY; + } + } +} + void FTrivialKartGamepadInputProcessor::LatchStickUntilNeutral() { ActiveStickDir = ETrivialKartStickDir::None; StickRepeatRemaining = 0.0f; LatchedRepeatKeys = HeldPhysicalKeys; - if (FMath::Abs(CachedLeftX) >= StickReleaseThreshold || FMath::Abs(CachedLeftY) >= StickReleaseThreshold) + float CurrentLeftX = 0.0f; + float CurrentLeftY = 0.0f; + GetDominantStickAxes(CurrentLeftX, CurrentLeftY); + if (FMath::Abs(CurrentLeftX) >= StickReleaseThreshold || FMath::Abs(CurrentLeftY) >= StickReleaseThreshold) { bLatchUntilNeutral = true; } @@ -146,6 +268,9 @@ void FTrivialKartGamepadInputProcessor::OnApplicationActivationChanged(const boo ETrivialKartStickDir FTrivialKartGamepadInputProcessor::ComputeDesiredStickDir() const { + float CachedLeftX = 0.0f; + float CachedLeftY = 0.0f; + GetDominantStickAxes(CachedLeftX, CachedLeftY); const float AbsX = FMath::Abs(CachedLeftX); const float AbsY = FMath::Abs(CachedLeftY); @@ -228,7 +353,15 @@ void FTrivialKartGamepadInputProcessor::Tick(const float DeltaTime, FSlateApplic #if WITH_EDITOR if (!OwnerController->IsGameViewportFocused()) { - if (ActiveStickDir != ETrivialKartStickDir::None || ConsumedPressedKeys.Num() > 0) + if (ActiveStickDir != ETrivialKartStickDir::None || + ConsumedPressedKeys.Num() > 0 || + HeldPhysicalKeys.Num() > 0 || + bIsPrimaryMouseHeld || + bIsPrimaryTouchHeld || + GetMaxTriggerAnalog(false) > 0.0f || + GetMaxTriggerAnalog(true) > 0.0f || + IsDigitalTriggerHeld(false) || + IsDigitalTriggerHeld(true)) { ResetState(); } @@ -236,9 +369,25 @@ void FTrivialKartGamepadInputProcessor::Tick(const float DeltaTime, FSlateApplic } #endif + // Confirm digital-only trigger devices (e.g. Switch Pro) once a full frame passes with digital trigger held and zero analog trigger axis + for (TPair& Pair : DeviceStates) + { + FTrivialKartDeviceInputState& DevState = Pair.Value; + if (DevState.TriggerSignature == ETrivialKartDeviceTriggerSignature::Unknown && + (DevState.bDigitalLeftTriggerHeld || DevState.bDigitalRightTriggerHeld) && + !DevState.bHasLeftTriggerAnalog && !DevState.bHasRightTriggerAnalog) + { + DevState.TriggerSignature = ETrivialKartDeviceTriggerSignature::SwitchDigitalOnly; + OwnerController->NotifyGamepadHardwareSignatureUpdated(Pair.Key); + } + } + if (bLatchUntilNeutral) { - if (FMath::Abs(CachedLeftX) < StickReleaseThreshold && FMath::Abs(CachedLeftY) < StickReleaseThreshold) + float CurrentLeftX = 0.0f; + float CurrentLeftY = 0.0f; + GetDominantStickAxes(CurrentLeftX, CurrentLeftY); + if (FMath::Abs(CurrentLeftX) < StickReleaseThreshold && FMath::Abs(CurrentLeftY) < StickReleaseThreshold) { bLatchUntilNeutral = false; } @@ -328,24 +477,86 @@ bool FTrivialKartGamepadInputProcessor::HandleAnalogInputEvent(FSlateApplication } #endif + const FInputDeviceId SourceDeviceId = InAnalogInputEvent.GetInputDeviceId(); + const bool bIsNewlyDiscoveredGamepad = Key.IsGamepadKey() && SourceDeviceId.IsValid() && !DeviceStates.Contains(SourceDeviceId); + FTrivialKartDeviceInputState& DevState = DeviceStates.FindOrAdd(SourceDeviceId); + if (bIsNewlyDiscoveredGamepad) + { + OwnerController->NotifyGamepadDeviceDiscovered(SourceDeviceId); + } + const float Value = InAnalogInputEvent.GetAnalogValue(); const float AbsValue = FMath::Abs(Value); if (Key == EKeys::Gamepad_LeftX) { - CachedLeftX = Value; + DevState.LeftX = Value; } else if (Key == EKeys::Gamepad_LeftY) { - CachedLeftY = Value; + DevState.LeftY = Value; } - else if (Key == EKeys::Gamepad_LeftTriggerAxis) + else if (Key == EKeys::Gamepad_LeftTriggerAxis || Key == EKeys::Gamepad_RightTriggerAxis) { - CachedLeftTrigger = Value; - } - else if (Key == EKeys::Gamepad_RightTriggerAxis) - { - CachedRightTrigger = Value; + const bool bIsLeft = (Key == EKeys::Gamepad_LeftTriggerAxis); + if (bIsLeft) + { + DevState.LeftTriggerAnalog = Value; + } + else + { + DevState.RightTriggerAnalog = Value; + } + + if (AbsValue > KINDA_SMALL_NUMBER) + { + if (bIsLeft) + { + DevState.bHasLeftTriggerAnalog = true; + DevState.bDigitalLeftTriggerHeld = false; + } + else + { + DevState.bHasRightTriggerAnalog = true; + DevState.bDigitalRightTriggerHeld = false; + } + + const FTrivialKartDeviceKey DigitalDevKey{ SourceDeviceId, bIsLeft ? EKeys::Gamepad_LeftTrigger : EKeys::Gamepad_RightTrigger }; + if (HeldPhysicalKeys.Remove(DigitalDevKey) > 0) + { + LatchedRepeatKeys.Remove(DigitalDevKey); + ConsumedPressedKeys.Add(DigitalDevKey); + } + } + + if ((DevState.bHasLeftTriggerAnalog || DevState.bHasRightTriggerAnalog) && Value >= 0.0f && Value < 0.30f) + { + DevState.bSawSubHalfTrigger = true; + if (DevState.TriggerSignature != ETrivialKartDeviceTriggerSignature::AnalogTriggerCapable) + { + DevState.TriggerSignature = ETrivialKartDeviceTriggerSignature::AnalogTriggerCapable; + OwnerController->NotifyGamepadHardwareSignatureUpdated(SourceDeviceId); + } + } + else if (!DevState.bSawSubHalfTrigger && + DevState.bHasLeftTriggerAnalog && + DevState.bHasRightTriggerAnalog && + FMath::IsWithinInclusive(DevState.LeftTriggerAnalog, 0.46f, 0.54f) && + FMath::IsWithinInclusive(DevState.RightTriggerAnalog, 0.46f, 0.54f)) + { + if (DevState.TriggerSignature != ETrivialKartDeviceTriggerSignature::PlayStationHalfRest) + { + DevState.TriggerSignature = ETrivialKartDeviceTriggerSignature::PlayStationHalfRest; + OwnerController->NotifyGamepadHardwareSignatureUpdated(SourceDeviceId); + } + } + else if (DevState.TriggerSignature == ETrivialKartDeviceTriggerSignature::Unknown && + AbsValue > KINDA_SMALL_NUMBER && + !(!DevState.bSawSubHalfTrigger && FMath::IsWithinInclusive(Value, 0.46f, 0.54f))) + { + DevState.TriggerSignature = ETrivialKartDeviceTriggerSignature::AnalogTriggerCapable; + OwnerController->NotifyGamepadHardwareSignatureUpdated(SourceDeviceId); + } } const bool bIsStickActive = (Key == EKeys::Gamepad_LeftX || Key == EKeys::Gamepad_LeftY) && (AbsValue >= GamepadModeStickThreshold); @@ -356,11 +567,12 @@ bool FTrivialKartGamepadInputProcessor::HandleAnalogInputEvent(FSlateApplication { LastGamepadActivityTimeSeconds = FPlatformTime::Seconds(); AccumulatedMouseDelta = FVector2D::ZeroVector; - OwnerController->NotifyExplicitDeviceInput(ETrivialKartInputMode::Gamepad); + OwnerController->NotifyExplicitGamepadInput(SourceDeviceId); - if (bIsTriggerPulled && !OwnerController->IsSubMenuOpen()) + if (bIsTriggerPulled && !OwnerController->IsSubMenuOpen() && !OwnerController->IsLoadingOpen()) { OwnerController->ClearPlayBoardMenuFocus(); + OwnerController->RestoreFocusToGameViewport(); } } @@ -379,23 +591,65 @@ bool FTrivialKartGamepadInputProcessor::HandleMouseButtonDownEvent(FSlateApplica return false; } + const FVector2D ScreenPos = MouseEvent.GetScreenSpacePosition(); #if WITH_EDITOR - if (!OwnerController->IsScreenPositionInGameViewport(MouseEvent.GetScreenSpacePosition())) + if (!OwnerController->IsScreenPositionInGameViewport(ScreenPos)) { return false; } #endif AccumulatedMouseDelta = FVector2D::ZeroVector; + if (MouseEvent.IsTouchEvent()) + { + if (OwnerController->IsGamepadAttached() && TouchPosIsCornerPhantom(ScreenPos)) + { + return false; + } + } + OwnerController->NotifyPointerDeviceInput(MouseEvent.IsTouchEvent() ? ETrivialKartInputMode::Touch : ETrivialKartInputMode::KeyboardMouse); - OwnerController->NotifyViewportPointerDown(MouseEvent.GetScreenSpacePosition()); + if (!OwnerController->IsLoadingOpen()) + { + OwnerController->NotifyViewportPointerDown(ScreenPos); + } + + const bool bBlockedByUI = OwnerController->IsUIBlockingInput() || OwnerController->IsPointOverPlayBoardMenuButton(ScreenPos); + if (MouseEvent.IsTouchEvent()) + { + bIsPrimaryMouseHeld = false; + if (MouseEvent.GetPointerIndex() >= 3 || bBlockedByUI) + { + bIsPrimaryTouchHeld = false; + } + else if (MouseEvent.GetPointerIndex() == 0) + { + bIsPrimaryTouchHeld = true; + } + } + else + { + bIsPrimaryTouchHeld = false; + if (MouseEvent.GetEffectingButton() == EKeys::LeftMouseButton) + { + bIsPrimaryMouseHeld = !bBlockedByUI; + } + } return false; } bool FTrivialKartGamepadInputProcessor::HandleMouseButtonUpEvent(FSlateApplication& SlateApp, const FPointerEvent& MouseEvent) { + if (MouseEvent.IsTouchEvent() && MouseEvent.GetPointerIndex() == 0) + { + bIsPrimaryTouchHeld = false; + } + else if (!MouseEvent.IsTouchEvent() && MouseEvent.GetEffectingButton() == EKeys::LeftMouseButton) + { + bIsPrimaryMouseHeld = false; + } return false; } @@ -456,26 +710,96 @@ bool FTrivialKartGamepadInputProcessor::ProcessKeyEvent(const FKeyEvent& InKeyEv return false; } + const FInputDeviceId SourceDeviceId = InKeyEvent.GetInputDeviceId(); + const FTrivialKartDeviceKey DevKey{ SourceDeviceId, RawKey }; + #if WITH_EDITOR if (!OwnerController->IsGameViewportFocused()) { if (!bIsPressed) { - ConsumedPressedKeys.Remove(RawKey); - HeldPhysicalKeys.Remove(RawKey); - LatchedRepeatKeys.Remove(RawKey); + ConsumedPressedKeys.Remove(DevKey); + HeldPhysicalKeys.Remove(DevKey); + LatchedRepeatKeys.Remove(DevKey); + if (FTrivialKartDeviceInputState* DevState = DeviceStates.Find(SourceDeviceId)) + { + if (RawKey == EKeys::Gamepad_LeftTrigger) + { + DevState->bDigitalLeftTriggerHeld = false; + } + else if (RawKey == EKeys::Gamepad_RightTrigger) + { + DevState->bDigitalRightTriggerHeld = false; + } + } } return false; } #endif - // Block premature digital trigger keys synthesized on Android DualSense (+0.50f resting) before real trigger travel (>= 0.65f) + if (RawKey.IsGamepadKey() && SourceDeviceId.IsValid() && !DeviceStates.Contains(SourceDeviceId)) + { + DeviceStates.Add(SourceDeviceId); + OwnerController->NotifyGamepadDeviceDiscovered(SourceDeviceId); + } + + // Track trigger capabilities per FInputDeviceId so analog-trigger devices (DualSense +0.50f, Xbox) suppress + // their own redundant digital trigger keys without suppressing digital-only Switch Pro / Joy-Con triggers. if (RawKey == EKeys::Gamepad_LeftTrigger || RawKey == EKeys::Gamepad_RightTrigger) { - const float CachedAxis = (RawKey == EKeys::Gamepad_LeftTrigger) ? CachedLeftTrigger : CachedRightTrigger; - if (bIsPressed && CachedAxis < GamepadTriggerActiveThreshold) + FTrivialKartDeviceInputState& DevState = DeviceStates.FindOrAdd(SourceDeviceId); + const bool bIsLeft = (RawKey == EKeys::Gamepad_LeftTrigger); + const bool bHasDeviceAnalogAxis = bIsLeft ? DevState.bHasLeftTriggerAnalog : DevState.bHasRightTriggerAnalog; + + if (bIsPressed) { - return true; + if (bHasDeviceAnalogAxis || (InKeyEvent.IsRepeat() && !HeldPhysicalKeys.Contains(DevKey))) + { + HeldPhysicalKeys.Remove(DevKey); + LatchedRepeatKeys.Remove(DevKey); + ConsumedPressedKeys.Add(DevKey); + return true; + } + + if (!InKeyEvent.IsRepeat()) + { + if (bIsLeft) + { + DevState.bDigitalLeftTriggerHeld = true; + } + else + { + DevState.bDigitalRightTriggerHeld = true; + } + } + } + else + { + const bool bWasDigitalHeld = bIsLeft ? DevState.bDigitalLeftTriggerHeld : DevState.bDigitalRightTriggerHeld; + if (bIsLeft) + { + DevState.bDigitalLeftTriggerHeld = false; + } + else + { + DevState.bDigitalRightTriggerHeld = false; + } + + if (bWasDigitalHeld && + !DevState.bHasLeftTriggerAnalog && + !DevState.bHasRightTriggerAnalog && + DevState.TriggerSignature == ETrivialKartDeviceTriggerSignature::Unknown) + { + DevState.TriggerSignature = ETrivialKartDeviceTriggerSignature::SwitchDigitalOnly; + OwnerController->NotifyGamepadHardwareSignatureUpdated(SourceDeviceId); + } + + if (bHasDeviceAnalogAxis && ConsumedPressedKeys.Remove(DevKey) > 0) + { + HeldPhysicalKeys.Remove(DevKey); + LatchedRepeatKeys.Remove(DevKey); + return true; + } } } @@ -488,17 +812,20 @@ bool FTrivialKartGamepadInputProcessor::ProcessKeyEvent(const FKeyEvent& InKeyEv || RawKey == EKeys::Gamepad_LeftStick_Left || (RawKey == EKeys::Gamepad_LeftStick_Right && OwnerController->IsUIBlockingInput()); - if (bIsSynthesizedStickMenuKey || (!bIsPressed && RawKey == EKeys::Gamepad_LeftStick_Right && ConsumedPressedKeys.Contains(RawKey))) + if (bIsSynthesizedStickMenuKey || (!bIsPressed && RawKey == EKeys::Gamepad_LeftStick_Right && ConsumedPressedKeys.Contains(DevKey))) { if (bIsPressed) { - LastGamepadActivityTimeSeconds = FPlatformTime::Seconds(); - AccumulatedMouseDelta = FVector2D::ZeroVector; - OwnerController->NotifyExplicitDeviceInput(ETrivialKartInputMode::Gamepad); - ConsumedPressedKeys.Add(RawKey); + if (!InKeyEvent.IsRepeat()) + { + LastGamepadActivityTimeSeconds = FPlatformTime::Seconds(); + AccumulatedMouseDelta = FVector2D::ZeroVector; + OwnerController->NotifyExplicitGamepadInput(SourceDeviceId); + } + ConsumedPressedKeys.Add(DevKey); return true; } - const bool bWasConsumed = ConsumedPressedKeys.Remove(RawKey) > 0; + const bool bWasConsumed = ConsumedPressedKeys.Remove(DevKey) > 0; return (RawKey != EKeys::Gamepad_LeftStick_Right) || bWasConsumed; } @@ -508,10 +835,10 @@ bool FTrivialKartGamepadInputProcessor::ProcessKeyEvent(const FKeyEvent& InKeyEv { if (!InKeyEvent.IsRepeat()) { - HeldPhysicalKeys.Add(RawKey); - LatchedRepeatKeys.Remove(RawKey); + HeldPhysicalKeys.Add(DevKey); + LatchedRepeatKeys.Remove(DevKey); } - if (InKeyEvent.IsRepeat() && (ConsumedPressedKeys.Contains(RawKey) || LatchedRepeatKeys.Contains(RawKey))) + if (InKeyEvent.IsRepeat() && (ConsumedPressedKeys.Contains(DevKey) || LatchedRepeatKeys.Contains(DevKey))) { return true; } @@ -526,14 +853,14 @@ bool FTrivialKartGamepadInputProcessor::ProcessKeyEvent(const FKeyEvent& InKeyEv const bool bHandled = OwnerController->HandleUICancelKey(true); if (bHandled) { - ConsumedPressedKeys.Add(RawKey); + ConsumedPressedKeys.Add(DevKey); } return bHandled; } - HeldPhysicalKeys.Remove(RawKey); - LatchedRepeatKeys.Remove(RawKey); - const bool bWasConsumed = ConsumedPressedKeys.Remove(RawKey) > 0; + HeldPhysicalKeys.Remove(DevKey); + LatchedRepeatKeys.Remove(DevKey); + const bool bWasConsumed = ConsumedPressedKeys.Remove(DevKey) > 0; const bool bHandled = bWasConsumed ? OwnerController->HandleUICancelKey(false) : false; return bHandled || bWasConsumed; } @@ -542,27 +869,27 @@ bool FTrivialKartGamepadInputProcessor::ProcessKeyEvent(const FKeyEvent& InKeyEv { if (!InKeyEvent.IsRepeat()) { - HeldPhysicalKeys.Add(RawKey); - LatchedRepeatKeys.Remove(RawKey); + HeldPhysicalKeys.Add(DevKey); + LatchedRepeatKeys.Remove(DevKey); } - if (RawKey.IsGamepadKey()) + if (!InKeyEvent.IsRepeat() && IsExplicitGamepadPromptSwitchKey(RawKey)) { LastGamepadActivityTimeSeconds = FPlatformTime::Seconds(); AccumulatedMouseDelta = FVector2D::ZeroVector; - OwnerController->NotifyExplicitDeviceInput(ETrivialKartInputMode::Gamepad); + OwnerController->NotifyExplicitGamepadInput(SourceDeviceId); } else if (IsGenuineKeyboardKey(RawKey)) { OwnerController->NotifyExplicitDeviceInput(ETrivialKartInputMode::KeyboardMouse); } - if (InKeyEvent.IsRepeat() && LatchedRepeatKeys.Contains(RawKey)) + if (InKeyEvent.IsRepeat() && LatchedRepeatKeys.Contains(DevKey)) { return true; } - if (InKeyEvent.IsRepeat() && ConsumedPressedKeys.Contains(RawKey) && !OwnerController->IsUIBlockingInput()) + if (InKeyEvent.IsRepeat() && ConsumedPressedKeys.Contains(DevKey) && !OwnerController->IsUIBlockingInput()) { return true; } @@ -573,20 +900,21 @@ bool FTrivialKartGamepadInputProcessor::ProcessKeyEvent(const FKeyEvent& InKeyEv const bool bBlockSlateLeak = (OwnerController->IsUIBlockingInput() && IsSlateNavigationLeakKey(RawKey)) || bBlockUnfocusedActivationLeak; if (bHandled || bBlockSlateLeak) { - ConsumedPressedKeys.Add(RawKey); + ConsumedPressedKeys.Add(DevKey); return true; } - if (RawKey == EKeys::SpaceBar) + if (!OwnerController->IsUIBlockingInput() && + (RawKey == EKeys::SpaceBar || RawKey == EKeys::Gamepad_LeftTrigger || RawKey == EKeys::Gamepad_RightTrigger)) { OwnerController->RestoreFocusToGameViewport(); } return false; } - HeldPhysicalKeys.Remove(RawKey); - LatchedRepeatKeys.Remove(RawKey); - const bool bWasConsumed = ConsumedPressedKeys.Remove(RawKey) > 0; + HeldPhysicalKeys.Remove(DevKey); + LatchedRepeatKeys.Remove(DevKey); + const bool bWasConsumed = ConsumedPressedKeys.Remove(DevKey) > 0; const bool bHandled = OwnerController->HandleGamepadKey(RawKey, false, false, InKeyEvent.IsShiftDown()); return bHandled || bWasConsumed; } diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Controllers/TrivialKartPlayerController.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Controllers/TrivialKartPlayerController.cpp index acaba458..55d9fc36 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Controllers/TrivialKartPlayerController.cpp +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Controllers/TrivialKartPlayerController.cpp @@ -24,28 +24,171 @@ #include "Engine/LocalPlayer.h" #include "EnhancedActionKeyMapping.h" #include "EnhancedInputSubsystems.h" +#include "EnhancedPlayerInput.h" #include "Framework/Application/SlateApplication.h" +#include "GameFramework/InputDeviceSubsystem.h" #include "GenericPlatform/GenericApplication.h" -#include "GenericPlatform/GenericPlatformInputDeviceMapper.h" #include "HAL/PlatformTime.h" #include "InputAction.h" #include "InputActionValue.h" #include "InputMappingContext.h" +#include "Kismet/KismetSystemLibrary.h" #include "UObject/ConstructorHelpers.h" +#include "Widgets/PlayBoardWidget.h" #include "Widgets/SViewport.h" -#include "Widgets/SWidget.h" +#if PLATFORM_ANDROID +#include "Android/AndroidApplication.h" +#include "Android/AndroidJNI.h" +#endif + +namespace +{ +#if PLATFORM_ANDROID + bool ClearPendingJniException(JNIEnv* Env) + { + if (Env && Env->ExceptionCheck()) + { + Env->ExceptionClear(); + return true; + } + return false; + } + + struct FAndroidInputDeviceJniCache + { + jclass InputDeviceClass = nullptr; + jmethodID GetDeviceIdsMethod = nullptr; + jmethodID GetDeviceMethod = nullptr; + jmethodID GetSourcesMethod = nullptr; + jmethodID GetVendorIdMethod = nullptr; + jmethodID GetControllerNumberMethod = nullptr; + jmethodID IsVirtualMethod = nullptr; + jmethodID GetNameMethod = nullptr; + bool bInitialized = false; + bool bValid = false; + + bool EnsureInitialized(JNIEnv* Env) + { + if (bInitialized) + { + return bValid; + } + bInitialized = true; + if (!Env) + { + return false; + } + + jclass LocalClass = Env->FindClass("android/view/InputDevice"); + if (ClearPendingJniException(Env) || !LocalClass) + { + return false; + } + + InputDeviceClass = static_cast(Env->NewGlobalRef(LocalClass)); + Env->DeleteLocalRef(LocalClass); + if (ClearPendingJniException(Env) || !InputDeviceClass) + { + InputDeviceClass = nullptr; + return false; + } + + GetDeviceIdsMethod = Env->GetStaticMethodID(InputDeviceClass, "getDeviceIds", "()[I"); + if (ClearPendingJniException(Env) || !GetDeviceIdsMethod) return false; + + GetDeviceMethod = Env->GetStaticMethodID(InputDeviceClass, "getDevice", "(I)Landroid/view/InputDevice;"); + if (ClearPendingJniException(Env) || !GetDeviceMethod) return false; + + GetSourcesMethod = Env->GetMethodID(InputDeviceClass, "getSources", "()I"); + if (ClearPendingJniException(Env) || !GetSourcesMethod) return false; + + GetVendorIdMethod = Env->GetMethodID(InputDeviceClass, "getVendorId", "()I"); + if (ClearPendingJniException(Env) || !GetVendorIdMethod) return false; + + GetControllerNumberMethod = Env->GetMethodID(InputDeviceClass, "getControllerNumber", "()I"); + if (ClearPendingJniException(Env)) + { + GetControllerNumberMethod = nullptr; + } -FInputActionValue UTrivialKartPositiveTriggerModifier::ModifyRaw_Implementation( + IsVirtualMethod = Env->GetMethodID(InputDeviceClass, "isVirtual", "()Z"); + if (ClearPendingJniException(Env) || !IsVirtualMethod) return false; + + GetNameMethod = Env->GetMethodID(InputDeviceClass, "getName", "()Ljava/lang/String;"); + if (ClearPendingJniException(Env) || !GetNameMethod) return false; + + bValid = true; + return true; + } + }; + + FAndroidInputDeviceJniCache GAndroidInputDeviceJni; +#endif +} + +FInputActionValue UTrivialKartDriveInputModifier::ModifyRaw_Implementation( const UEnhancedPlayerInput* PlayerInput, FInputActionValue CurrentValue, float DeltaTime) { - const float RawAxis = CurrentValue.Get(); - if (RawAxis >= ActiveThreshold) + const FInputActionValue ZeroValue(CurrentValue.GetValueType(), FVector::ZeroVector); + if (!PlayerInput) + { + return ZeroValue; + } + + const ATrivialKartPlayerController* PC = Cast(PlayerInput->GetOuterAPlayerController()); + if (!PC || !PC->IsGameplayDrivingAllowed()) { - return CurrentValue; + return ZeroValue; + } + + switch (GateRule) + { + case ETrivialKartDriveGateRule::StandardKey: + return (CurrentValue.Get() > 0.0f) ? CurrentValue : ZeroValue; + + case ETrivialKartDriveGateRule::AnalogTriggerAxis: + { + float RawAxis = PC->GetTriggerAnalogValue(TargetKey); + if (CurrentValue.GetValueType() != EInputActionValueType::Boolean) + { + RawAxis = FMath::Max(RawAxis, CurrentValue.Get()); + } + if (RawAxis >= ActiveThreshold) + { + return (CurrentValue.GetValueType() == EInputActionValueType::Boolean) + ? FInputActionValue(true) + : FInputActionValue(RawAxis); + } + return ZeroValue; + } + + case ETrivialKartDriveGateRule::DigitalTriggerKey: + if (PC->IsDigitalTriggerHeld(TargetKey)) + { + return (CurrentValue.GetValueType() == EInputActionValueType::Boolean) + ? FInputActionValue(true) + : FInputActionValue(1.0f); + } + return ZeroValue; + + case ETrivialKartDriveGateRule::TouchHold: + return (CurrentValue.Get() > 0.0f && + PC->GetActiveInputMode() == ETrivialKartInputMode::Touch && + PC->IsPrimaryTouchHeld()) + ? CurrentValue + : ZeroValue; + + case ETrivialKartDriveGateRule::MouseHold: + return (CurrentValue.Get() > 0.0f && + PC->GetActiveInputMode() == ETrivialKartInputMode::KeyboardMouse && + PC->IsPrimaryMouseHeld()) + ? CurrentValue + : ZeroValue; } - return FInputActionValue(CurrentValue.GetValueType(), FVector::ZeroVector); + + return ZeroValue; } ATrivialKartPlayerController::ATrivialKartPlayerController() @@ -74,9 +217,18 @@ void ATrivialKartPlayerController::BeginPlay() RemapAllDevicesToPrimaryUser(); + if (FSlateApplication::IsInitialized()) + { + GamepadInputProcessor = MakeShared(this); + FSlateApplication::Get().RegisterInputPreProcessor(GamepadInputProcessor, 0); + } + + RefreshAndroidGamepadSnapshot(); + bWasGamepadAttached = QueryAnyGamepadAttached(); if (bWasGamepadAttached) { + RefreshGamepadStyleForDevice(INPUTDEVICEID_NONE, false); SetActiveInputMode(ETrivialKartInputMode::Gamepad); } @@ -86,12 +238,6 @@ void ATrivialKartPlayerController::BeginPlay() PeriodicDevicePollHandle = FTSTicker::GetCoreTicker().AddTicker( FTickerDelegate::CreateUObject(this, &ATrivialKartPlayerController::PollDeviceConnectionState), 0.75f); - - if (FSlateApplication::IsInitialized()) - { - GamepadInputProcessor = MakeShared(this); - FSlateApplication::Get().RegisterInputPreProcessor(GamepadInputProcessor, 0); - } } void ATrivialKartPlayerController::EndPlay(const EEndPlayReason::Type EndPlayReason) @@ -130,14 +276,8 @@ UInputMappingContext* ATrivialKartPlayerController::GetOrCreateGameplayMappingCo return nullptr; } - RuntimeGameplayMappingContext = DuplicateObject(DefaultMappingContext, this); - if (!RuntimeGameplayMappingContext) - { - return DefaultMappingContext; - } - const UInputAction* MoveAction = nullptr; - for (const FEnhancedActionKeyMapping& Existing : RuntimeGameplayMappingContext->GetMappings()) + for (const FEnhancedActionKeyMapping& Existing : DefaultMappingContext->GetMappings()) { if (Existing.Action) { @@ -148,59 +288,66 @@ UInputMappingContext* ATrivialKartPlayerController::GetOrCreateGameplayMappingCo if (!MoveAction) { - return RuntimeGameplayMappingContext; + return DefaultMappingContext; } - auto HasKeyMapped = [this, MoveAction](const FKey& Key) -> bool + // Build a clean runtime context from scratch so DefaultMappingContext's unguarded Touch1 + // (which lacks FKeyDetails::TouchKey and stays latched true on Android DualSense) cannot survive. + RuntimeGameplayMappingContext = NewObject(this); + if (!RuntimeGameplayMappingContext) + { + return DefaultMappingContext; + } + + auto MapDriveKeyWithRule = [this, MoveAction](const FKey& Key, ETrivialKartDriveGateRule Rule, const FKey& RuleTargetKey = EKeys::Invalid) { - for (const FEnhancedActionKeyMapping& Mapping : RuntimeGameplayMappingContext->GetMappings()) + if (!Key.IsValid()) { - if (Mapping.Action == MoveAction && Mapping.Key == Key) - { - return true; - } + return; + } + FEnhancedActionKeyMapping& Mapping = RuntimeGameplayMappingContext->MapKey(MoveAction, Key); + if (UTrivialKartDriveInputModifier* Modifier = NewObject(RuntimeGameplayMappingContext)) + { + Modifier->GateRule = Rule; + Modifier->TargetKey = RuleTargetKey; + Mapping.Modifiers.Add(Modifier); } - return false; }; + MapDriveKeyWithRule(EKeys::TouchKeys[0], ETrivialKartDriveGateRule::TouchHold); + MapDriveKeyWithRule(EKeys::LeftMouseButton, ETrivialKartDriveGateRule::MouseHold); + + UTrivialKartDriveInputModifier* SharedStandardGate = NewObject(RuntimeGameplayMappingContext); + if (SharedStandardGate) + { + SharedStandardGate->GateRule = ETrivialKartDriveGateRule::StandardKey; + } + const FKey StandardDriveKeys[] = { EKeys::Gamepad_FaceButton_Bottom, EKeys::Gamepad_DPad_Right, EKeys::Gamepad_LeftStick_Right, EKeys::SpaceBar, - EKeys::Right, - EKeys::LeftMouseButton, - EKeys::TouchKeys[0] + EKeys::Right }; for (const FKey& Key : StandardDriveKeys) { - if (Key.IsValid() && !HasKeyMapped(Key)) + if (Key.IsValid()) { - RuntimeGameplayMappingContext->MapKey(MoveAction, Key); - } - } - - UTrivialKartPositiveTriggerModifier* TriggerModifier = - NewObject(RuntimeGameplayMappingContext); - - const FKey TriggerAxisKeys[] = { - EKeys::Gamepad_LeftTriggerAxis, - EKeys::Gamepad_RightTriggerAxis - }; - - for (const FKey& AxisKey : TriggerAxisKeys) - { - if (AxisKey.IsValid() && !HasKeyMapped(AxisKey)) - { - FEnhancedActionKeyMapping& TriggerMapping = RuntimeGameplayMappingContext->MapKey(MoveAction, AxisKey); - if (TriggerModifier) + FEnhancedActionKeyMapping& KeyMapping = RuntimeGameplayMappingContext->MapKey(MoveAction, Key); + if (SharedStandardGate) { - TriggerMapping.Modifiers.Add(TriggerModifier); + KeyMapping.Modifiers.Add(SharedStandardGate); } } } + MapDriveKeyWithRule(EKeys::Gamepad_LeftTrigger, ETrivialKartDriveGateRule::DigitalTriggerKey, EKeys::Gamepad_LeftTrigger); + MapDriveKeyWithRule(EKeys::Gamepad_RightTrigger, ETrivialKartDriveGateRule::DigitalTriggerKey, EKeys::Gamepad_RightTrigger); + MapDriveKeyWithRule(EKeys::Gamepad_LeftTriggerAxis, ETrivialKartDriveGateRule::AnalogTriggerAxis, EKeys::Gamepad_LeftTriggerAxis); + MapDriveKeyWithRule(EKeys::Gamepad_RightTriggerAxis, ETrivialKartDriveGateRule::AnalogTriggerAxis, EKeys::Gamepad_RightTriggerAxis); + return RuntimeGameplayMappingContext; } @@ -208,71 +355,21 @@ void ATrivialKartPlayerController::SetupInputComponent() { Super::SetupInputComponent(); - if (IsLocalPlayerController() && bGameplayInputEnabled) + if (IsLocalPlayerController()) { if (UInputMappingContext* GameplayMC = GetOrCreateGameplayMappingContext()) { if (UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem(GetLocalPlayer())) { - Subsystem->AddMappingContext(GameplayMC, 0); + FModifyContextOptions Options; + Options.bForceImmediately = true; + Options.bIgnoreAllPressedKeysUntilRelease = false; + Subsystem->AddMappingContext(GameplayMC, 0, Options); } } } } -FKey ATrivialKartPlayerController::ResolveCanonicalUIKey( - const UInputAction* Action, - const TArray& UIMappings) -{ - if (!Action) - { - return EKeys::Invalid; - } - - const FName ActionName = Action->GetFName(); - if (ActionName == TEXT("IA_UI_MoveUp")) - { - return EKeys::Gamepad_DPad_Up; - } - if (ActionName == TEXT("IA_UI_MoveDown")) - { - return EKeys::Gamepad_DPad_Down; - } - if (ActionName == TEXT("IA_UI_MoveLeft")) - { - return EKeys::Gamepad_DPad_Left; - } - if (ActionName == TEXT("IA_UI_MoveRight")) - { - return EKeys::Gamepad_DPad_Right; - } - if (ActionName == TEXT("IA_UI_Confirm")) - { - return EKeys::Gamepad_FaceButton_Bottom; - } - if (ActionName == TEXT("IA_UI_Cancel")) - { - return EKeys::Gamepad_FaceButton_Right; - } - if (ActionName == TEXT("IA_UI_PrevTab")) - { - return EKeys::Gamepad_LeftShoulder; - } - if (ActionName == TEXT("IA_UI_NextTab")) - { - return EKeys::Gamepad_RightShoulder; - } - - for (const FEnhancedActionKeyMapping& Candidate : UIMappings) - { - if (Candidate.Action == Action && Candidate.Key.IsGamepadKey()) - { - return Candidate.Key; - } - } - return EKeys::Invalid; -} - FKey ATrivialKartPlayerController::ResolveFallbackUIKey(const FKey& InKey, bool bIsShiftDown) { if (InKey == EKeys::Tab) @@ -322,6 +419,17 @@ bool ATrivialKartPlayerController::IsDirectionalUIKey(const FKey& Key) || Key == EKeys::Gamepad_DPad_Right; } +bool ATrivialKartPlayerController::IsDirectGameplayDriveKey(const FKey& Key) +{ + return Key == EKeys::Gamepad_FaceButton_Bottom + || Key == EKeys::Gamepad_DPad_Right + || Key == EKeys::Gamepad_LeftStick_Right + || Key == EKeys::SpaceBar + || Key == EKeys::Right + || Key == EKeys::Gamepad_LeftTrigger + || Key == EKeys::Gamepad_RightTrigger; +} + bool ATrivialKartPlayerController::HandleGamepadKey(const FKey& InKey, bool bIsPressed, bool bIsRepeat, bool bIsShiftDown) { ATrivialKartHUD* CurrentHUD = Cast(GetHUD()); @@ -330,41 +438,26 @@ bool ATrivialKartPlayerController::HandleGamepadKey(const FKey& InKey, bool bIsP return false; } - // SpaceBar on PlayBoard always drives the kart as instructed by the HUD banner, even if mouse hovers a bottom menu button - if (!IsSubMenuOpen() && InKey == EKeys::SpaceBar) + if (CurrentHUD->IsLoadingOpen()) { - if (bIsPressed) - { - CurrentHUD->ClearPlayBoardMenuFocus(); - } - return false; + return bIsPressed; } - FKey CanonicalKey = EKeys::Invalid; - bool bAllowRepeat = false; - - if (UIMappingContext && InKey != EKeys::Tab) + // Dedicated primary drive keys on PlayBoard always clear bottom-bar focus and drive the kart as instructed by the HUD banner + if (!IsSubMenuOpen() && + (InKey == EKeys::SpaceBar || InKey == EKeys::Gamepad_LeftTrigger || InKey == EKeys::Gamepad_RightTrigger)) { - const TArray& UIMappings = UIMappingContext->GetMappings(); - for (const FEnhancedActionKeyMapping& Mapping : UIMappings) + if (bIsPressed) { - if (Mapping.Key == InKey && Mapping.Action) - { - CanonicalKey = ResolveCanonicalUIKey(Mapping.Action, UIMappings); - bAllowRepeat = (Mapping.Action->ValueType != EInputActionValueType::Boolean) || IsDirectionalUIKey(CanonicalKey); - break; - } + CurrentHUD->ClearPlayBoardMenuFocus(); } + return false; } - if (!CanonicalKey.IsValid()) - { - CanonicalKey = ResolveFallbackUIKey(InKey, bIsShiftDown); - bAllowRepeat = IsDirectionalUIKey(CanonicalKey); - } - + const FKey CanonicalKey = ResolveFallbackUIKey(InKey, bIsShiftDown); if (CanonicalKey.IsValid()) { + const bool bAllowRepeat = IsDirectionalUIKey(CanonicalKey); if (bIsPressed && bIsRepeat && !bAllowRepeat) { return IsUIBlockingInput(); @@ -380,17 +473,9 @@ bool ATrivialKartPlayerController::HandleGamepadKey(const FKey& InKey, bool bIsP } } - UInputMappingContext* GameplayMC = GetOrCreateGameplayMappingContext(); - if (bIsPressed && GameplayMC && !IsUIBlockingInput()) + if (bIsPressed && !IsUIBlockingInput() && IsDirectGameplayDriveKey(InKey)) { - for (const FEnhancedActionKeyMapping& Mapping : GameplayMC->GetMappings()) - { - if (Mapping.Key == InKey) - { - CurrentHUD->ClearPlayBoardMenuFocus(); - break; - } - } + CurrentHUD->ClearPlayBoardMenuFocus(); } return false; @@ -405,6 +490,15 @@ bool ATrivialKartPlayerController::HandleUICancelKey(bool bIsPressed) return false; } +bool ATrivialKartPlayerController::IsLoadingOpen() const +{ + if (const ATrivialKartHUD* CurrentHUD = Cast(GetHUD())) + { + return CurrentHUD->IsLoadingOpen(); + } + return false; +} + bool ATrivialKartPlayerController::IsSubMenuOpen() const { if (const ATrivialKartHUD* CurrentHUD = Cast(GetHUD())) @@ -423,6 +517,17 @@ bool ATrivialKartPlayerController::IsUIBlockingInput() const return false; } +bool ATrivialKartPlayerController::IsGameplayDrivingAllowed() const +{ +#if WITH_EDITOR + if (!IsGameViewportFocused()) + { + return false; + } +#endif + return bGameplayInputEnabled && !IsUIBlockingInput(); +} + bool ATrivialKartPlayerController::IsStickNavigationEnabled() const { if (const ATrivialKartHUD* CurrentHUD = Cast(GetHUD())) @@ -432,27 +537,24 @@ bool ATrivialKartPlayerController::IsStickNavigationEnabled() const return false; } -void ATrivialKartPlayerController::SetGameplayInputEnabled(bool bEnabled) +bool ATrivialKartPlayerController::IsPointOverPlayBoardMenuButton(const FVector2D& ScreenSpacePosition) const { - UInputMappingContext* GameplayMC = GetOrCreateGameplayMappingContext(); - if (bGameplayInputEnabled == bEnabled || !GameplayMC) + if (ATrivialKartHUD* CurrentHUD = Cast(GetHUD())) { - return; + if (const UPlayBoardWidget* PlayBoard = Cast(CurrentHUD->GetWidgetOfType(EWidgetType::PlayBoard))) + { + return PlayBoard->IsPointOverAnyMenuButton(ScreenSpacePosition); + } } - bGameplayInputEnabled = bEnabled; + return false; +} - if (UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem(GetLocalPlayer())) +void ATrivialKartPlayerController::SetGameplayInputEnabled(bool bEnabled) +{ + bGameplayInputEnabled = bEnabled; + if (!bEnabled && GamepadInputProcessor.IsValid()) { - FModifyContextOptions Options; - Options.bForceImmediately = true; - if (bGameplayInputEnabled) - { - Subsystem->AddMappingContext(GameplayMC, 0, Options); - } - else - { - Subsystem->RemoveMappingContext(GameplayMC, Options); - } + GamepadInputProcessor->ClearPointerDriveHeld(); } } @@ -461,12 +563,58 @@ void ATrivialKartPlayerController::NotifyExplicitDeviceInput(ETrivialKartInputMo if (DetectedMode != ETrivialKartInputMode::Gamepad) { LastNonGamepadInputTimeSeconds = FPlatformTime::Seconds(); + SetActiveInputMode(DetectedMode); } - else +} + +void ATrivialKartPlayerController::NotifyExplicitGamepadInput(FInputDeviceId SourceDeviceId) +{ + if (SourceDeviceId.IsValid()) { - bKeyNavigationActive = true; + LastActiveGamepadDeviceId = SourceDeviceId; + } + + // Zero-allocation / zero-JNI fast path for 60-240Hz stick & trigger analog events + if (ActiveInputMode == ETrivialKartInputMode::Gamepad && + bKeyNavigationActive && + SourceDeviceId.IsValid()) + { + if (const ETrivialKartGamepadStyle* ConfirmedStyle = ConfirmedUnrealDeviceStyles.Find(SourceDeviceId)) + { + if (ActiveGamepadStyle != *ConfirmedStyle) + { + ActiveGamepadStyle = *ConfirmedStyle; + OnInputModeUpdated.Broadcast(ActiveInputMode); + } + return; + } + } + + bKeyNavigationActive = true; + RefreshGamepadStyleForDevice(LastActiveGamepadDeviceId, true); + SetActiveInputMode(ETrivialKartInputMode::Gamepad); +} + +void ATrivialKartPlayerController::NotifyGamepadDeviceDiscovered(FInputDeviceId SourceDeviceId) +{ + if (SourceDeviceId.IsValid() && !SeenUnrealGamepadDevices.Contains(SourceDeviceId)) + { + RefreshAndroidGamepadSnapshot(); + InvalidatePendingUnrealSlotEvaluations(); + ResolveGamepadStyleForDevice(SourceDeviceId); + } +} + +void ATrivialKartPlayerController::NotifyGamepadHardwareSignatureUpdated(FInputDeviceId SourceDeviceId) +{ + if (SourceDeviceId.IsValid()) + { + ResolveGamepadStyleForDevice(SourceDeviceId); + } + if (LastActiveGamepadDeviceId.IsValid()) + { + RefreshGamepadStyleForDevice(LastActiveGamepadDeviceId, true); } - SetActiveInputMode(DetectedMode); } void ATrivialKartPlayerController::NotifyPointerDeviceInput(ETrivialKartInputMode PointerMode) @@ -527,6 +675,11 @@ void ATrivialKartPlayerController::SetActiveInputMode(ETrivialKartInputMode NewM bKeyNavigationActive = true; } + if (NewMode != ETrivialKartInputMode::Touch && GamepadInputProcessor.IsValid()) + { + GamepadInputProcessor->ClearPrimaryTouchHeld(); + } + ActiveInputMode = NewMode; bShowMouseCursor = (ActiveInputMode == ETrivialKartInputMode::KeyboardMouse); OnInputModeUpdated.Broadcast(ActiveInputMode); @@ -564,6 +717,50 @@ void ATrivialKartPlayerController::LatchStickUntilNeutral() } } +float ATrivialKartPlayerController::GetTriggerAnalogValue(const FKey& TriggerAxisKey) const +{ + if (!GamepadInputProcessor.IsValid()) + { + return 0.0f; + } + if (TriggerAxisKey == EKeys::Gamepad_LeftTriggerAxis) + { + return GamepadInputProcessor->GetMaxTriggerAnalog(false); + } + if (TriggerAxisKey == EKeys::Gamepad_RightTriggerAxis) + { + return GamepadInputProcessor->GetMaxTriggerAnalog(true); + } + return 0.0f; +} + +bool ATrivialKartPlayerController::IsDigitalTriggerHeld(const FKey& DigitalTriggerKey) const +{ + if (!GamepadInputProcessor.IsValid()) + { + return false; + } + if (DigitalTriggerKey == EKeys::Gamepad_LeftTrigger) + { + return GamepadInputProcessor->IsDigitalTriggerHeld(false); + } + if (DigitalTriggerKey == EKeys::Gamepad_RightTrigger) + { + return GamepadInputProcessor->IsDigitalTriggerHeld(true); + } + return false; +} + +bool ATrivialKartPlayerController::IsPrimaryTouchHeld() const +{ + return GamepadInputProcessor.IsValid() && GamepadInputProcessor->IsPrimaryTouchHeld(); +} + +bool ATrivialKartPlayerController::IsPrimaryMouseHeld() const +{ + return GamepadInputProcessor.IsValid() && GamepadInputProcessor->IsPrimaryMouseHeld(); +} + void ATrivialKartPlayerController::RestoreFocusToGameViewport() { if (!FSlateApplication::IsInitialized()) @@ -576,6 +773,14 @@ void ATrivialKartPlayerController::RestoreFocusToGameViewport() { if (TSharedPtr ViewportWidget = ViewportClient->GetGameViewportWidget()) { +#if !WITH_EDITOR + const UGameInstance* GI = GetGameInstance(); + if (!GI || GI->GetNumLocalPlayers() <= 1) + { + FSlateApplication::Get().SetAllUserFocus(ViewportWidget, EFocusCause::SetDirectly); + return; + } +#endif FSlateApplication::Get().SetUserFocus(GetLocalPlayerUserIndex(), ViewportWidget, EFocusCause::SetDirectly); } } @@ -648,9 +853,15 @@ bool ATrivialKartPlayerController::IsScreenPositionInGameViewport(const FVector2 return false; } -bool ATrivialKartPlayerController::QueryAnyGamepadAttached() +bool ATrivialKartPlayerController::QueryAnyGamepadAttached() const { - if (!FSlateApplication::IsInitialized()) +#if PLATFORM_ANDROID + if (bHasInitialAndroidSnapshot && GAndroidInputDeviceJni.bValid) + { + return !CachedAndroidGamepads.IsEmpty(); + } +#endif + if (!FSlateApplication::IsInitialized()) { return false; } @@ -658,6 +869,820 @@ bool ATrivialKartPlayerController::QueryAnyGamepadAttached() return PlatformApp.IsValid() && PlatformApp->IsGamepadAttached(); } +void ATrivialKartPlayerController::InvalidatePendingUnrealSlotEvaluations() +{ + for (TPair& Pair : UnrealDeviceSlotBindings) + { + if (Pair.Value.SlotIndex == INDEX_NONE || !ConfirmedUnrealDeviceStyles.Contains(Pair.Key)) + { + Pair.Value.bEvaluated = false; + } + } +} + +void ATrivialKartPlayerController::EvictUnrealGamepadDevice(FInputDeviceId DeviceId) +{ + if (!DeviceId.IsValid()) + { + return; + } + if (const FTrivialKartUnrealSlotBinding* Bound = UnrealDeviceSlotBindings.Find(DeviceId)) + { + if (Bound->SlotIndex != INDEX_NONE) + { + ClaimedAndroidControllerSlots.Remove(Bound->SlotIndex); + } + UnrealDeviceSlotBindings.Remove(DeviceId); + } + if (LastActiveGamepadDeviceId == DeviceId) + { + LastActiveGamepadDeviceId = INPUTDEVICEID_NONE; + } + if (GamepadInputProcessor.IsValid()) + { + GamepadInputProcessor->RemoveDeviceState(DeviceId); + } + SeenUnrealGamepadDevices.Remove(DeviceId); + ConfirmedUnrealDeviceStyles.Remove(DeviceId); +} + +int32 ATrivialKartPlayerController::CountConnectedAndroidStyle(ETrivialKartGamepadStyle Style) const +{ + int32 Total = 0; + for (const FTrivialKartAndroidGamepadInfo& Info : CachedAndroidGamepads) + { + if (Info.Style == Style) + { + ++Total; + } + } + return Total; +} + +bool ATrivialKartPlayerController::TryPopUniformPendingHotplugStyle(ETrivialKartGamepadStyle& OutStyle) +{ + if (PendingHotplugStyles.IsEmpty()) + { + return false; + } + const ETrivialKartGamepadStyle CandidateStyle = PendingHotplugStyles[0]; + for (int32 i = 1; i < PendingHotplugStyles.Num(); ++i) + { + if (PendingHotplugStyles[i] != CandidateStyle) + { + return false; + } + } + PendingHotplugStyles.RemoveAt(0); + OutStyle = CandidateStyle; + return true; +} + +void ATrivialKartPlayerController::RefreshAndroidGamepadSnapshot() +{ +#if PLATFORM_ANDROID + CachedAndroidGamepads.Reset(); + + if (JNIEnv* Env = FAndroidApplication::GetJavaEnv()) + { + if (!GAndroidInputDeviceJni.EnsureInitialized(Env)) + { + return; + } + + jintArray DeviceIdsArray = static_cast( + Env->CallStaticObjectMethod(GAndroidInputDeviceJni.InputDeviceClass, GAndroidInputDeviceJni.GetDeviceIdsMethod)); + if (ClearPendingJniException(Env)) + { + DeviceIdsArray = nullptr; + } + + if (DeviceIdsArray) + { + const jsize Count = Env->GetArrayLength(DeviceIdsArray); + if (!ClearPendingJniException(Env) && Count > 0) + { + if (jint* DeviceIds = Env->GetIntArrayElements(DeviceIdsArray, nullptr)) + { + auto CollectMatchingDevices = [&](jint RequiredSourceMask) + { + for (jsize i = 0; i < Count; ++i) + { + const int32 AndroidDevId = static_cast(DeviceIds[i]); + jobject DevObj = Env->CallStaticObjectMethod( + GAndroidInputDeviceJni.InputDeviceClass, + GAndroidInputDeviceJni.GetDeviceMethod, + DeviceIds[i]); + if (ClearPendingJniException(Env) || !DevObj) + { + continue; + } + + const jboolean bIsVirtual = Env->CallBooleanMethod(DevObj, GAndroidInputDeviceJni.IsVirtualMethod); + if (ClearPendingJniException(Env) || bIsVirtual) + { + Env->DeleteLocalRef(DevObj); + continue; + } + + const jint Sources = Env->CallIntMethod(DevObj, GAndroidInputDeviceJni.GetSourcesMethod); + if (ClearPendingJniException(Env) || (Sources & RequiredSourceMask) != RequiredSourceMask) + { + Env->DeleteLocalRef(DevObj); + continue; + } + + const jint VendorId = Env->CallIntMethod(DevObj, GAndroidInputDeviceJni.GetVendorIdMethod); + if (ClearPendingJniException(Env)) + { + Env->DeleteLocalRef(DevObj); + continue; + } + + int32 ControllerNumber = 0; + if (GAndroidInputDeviceJni.GetControllerNumberMethod) + { + ControllerNumber = static_cast( + Env->CallIntMethod(DevObj, GAndroidInputDeviceJni.GetControllerNumberMethod)); + if (ClearPendingJniException(Env)) + { + ControllerNumber = 0; + } + } + + auto ReadJavaStringField = [&](jmethodID MethodId) -> FString + { + FString Result; + if (!MethodId) + { + return Result; + } + jstring JStr = static_cast(Env->CallObjectMethod(DevObj, MethodId)); + if (!ClearPendingJniException(Env) && JStr) + { + if (const char* UTFChars = Env->GetStringUTFChars(JStr, nullptr)) + { + Result = UTF8_TO_TCHAR(UTFChars); + Env->ReleaseStringUTFChars(JStr, UTFChars); + } + ClearPendingJniException(Env); + Env->DeleteLocalRef(JStr); + } + return Result; + }; + + FString DevName = ReadJavaStringField(GAndroidInputDeviceJni.GetNameMethod); + DevName.TrimStartAndEndInline(); + + // Skip auxiliary sensor / touchpad sub-devices registered alongside DualSense and Switch Pro + if (DevName.Contains(TEXT("Motion Sensors"), ESearchCase::IgnoreCase) || + DevName.Contains(TEXT("Touchpad"), ESearchCase::IgnoreCase) || + DevName.EndsWith(TEXT(" IMU"), ESearchCase::IgnoreCase)) + { + Env->DeleteLocalRef(DevObj); + continue; + } + + + ETrivialKartGamepadStyle DevStyle = ETrivialKartGamepadStyle::GenericXbox; + if (VendorId == 0x054c || + DevName.Contains(TEXT("DualSense"), ESearchCase::IgnoreCase) || + DevName.Contains(TEXT("DualShock"), ESearchCase::IgnoreCase) || + DevName.Contains(TEXT("PlayStation"), ESearchCase::IgnoreCase) || + DevName.Contains(TEXT("Sony"), ESearchCase::IgnoreCase)) + { + DevStyle = ETrivialKartGamepadStyle::PlayStation; + } + else if (VendorId == 0x057e || + DevName.Contains(TEXT("Nintendo"), ESearchCase::IgnoreCase) || + DevName.Contains(TEXT("Switch"), ESearchCase::IgnoreCase) || + DevName.Contains(TEXT("Joy-Con"), ESearchCase::IgnoreCase) || + DevName.Contains(TEXT("JoyCon"), ESearchCase::IgnoreCase) || + DevName.Contains(TEXT("Pro Controller"), ESearchCase::IgnoreCase)) + { + DevStyle = ETrivialKartGamepadStyle::NintendoSwitch; + } + + FTrivialKartAndroidGamepadInfo Info; + Info.AndroidDeviceId = AndroidDevId; + Info.ControllerNumber = ControllerNumber; + Info.VendorId = static_cast(VendorId); + Info.DeviceName = MoveTemp(DevName); + Info.Style = DevStyle; + CachedAndroidGamepads.Add(MoveTemp(Info)); + + Env->DeleteLocalRef(DevObj); + } + }; + + // Prefer strict SOURCE_GAMEPAD (0x00000401) so IMU/Motion-Sensor SOURCE_JOYSTICK sub-devices + // never duplicate DualSense or Switch Pro entries; fall back to SOURCE_JOYSTICK only if needed. + constexpr jint SourceGamepad = 0x00000401; + constexpr jint SourceJoystick = 0x01000010; + CollectMatchingDevices(SourceGamepad); + if (CachedAndroidGamepads.IsEmpty()) + { + CollectMatchingDevices(SourceJoystick); + } + + Env->ReleaseIntArrayElements(DeviceIdsArray, DeviceIds, JNI_ABORT); + } + else + { + ClearPendingJniException(Env); + } + } + Env->DeleteLocalRef(DeviceIdsArray); + } + } + + CachedAndroidGamepads.Sort([](const FTrivialKartAndroidGamepadInfo& A, const FTrivialKartAndroidGamepadInfo& B) + { + const int32 OrderA = (A.ControllerNumber > 0) ? A.ControllerNumber : MAX_int32; + const int32 OrderB = (B.ControllerNumber > 0) ? B.ControllerNumber : MAX_int32; + if (OrderA != OrderB) + { + return OrderA < OrderB; + } + return A.AndroidDeviceId < B.AndroidDeviceId; + }); + + // Revalidate cached Unreal controller-slot bindings (evict released or reassigned slots, and allow re-evaluation) + TArray> ReleasedSlotDevices; + for (TPair& Pair : UnrealDeviceSlotBindings) + { + if (Pair.Value.SlotIndex == INDEX_NONE) + { + Pair.Value.bEvaluated = false; + continue; + } + + FString CurrentSlotName = UKismetSystemLibrary::GetGamepadControllerName(Pair.Value.SlotIndex); + CurrentSlotName.TrimStartAndEndInline(); + if (CurrentSlotName.IsEmpty() || + CurrentSlotName.Equals(TEXT("None"), ESearchCase::IgnoreCase) || + (!Pair.Value.SlotName.IsEmpty() && !CurrentSlotName.Equals(Pair.Value.SlotName, ESearchCase::CaseSensitive))) + { + ReleasedSlotDevices.Add(Pair.Key); + } + else if (!ConfirmedUnrealDeviceStyles.Contains(Pair.Key)) + { + Pair.Value.bEvaluated = false; + } + } + for (FInputDeviceId ReleasedDeviceId : ReleasedSlotDevices) + { + EvictUnrealGamepadDevice(ReleasedDeviceId); + } + + if (!bHasInitialAndroidSnapshot) + { + bHasInitialAndroidSnapshot = true; + for (const FTrivialKartAndroidGamepadInfo& Info : CachedAndroidGamepads) + { + KnownAndroidDeviceStyles.Add(Info.AndroidDeviceId, Info.Style); + } + return; + } + + for (auto It = KnownAndroidDeviceStyles.CreateIterator(); It; ++It) + { + const int32 KnownId = It->Key; + const bool bStillPresent = CachedAndroidGamepads.ContainsByPredicate([KnownId](const FTrivialKartAndroidGamepadInfo& Info) + { + return Info.AndroidDeviceId == KnownId; + }); + if (!bStillPresent) + { + PendingHotplugStyles.RemoveSingle(It->Value); + It.RemoveCurrent(); + } + } + + for (const FTrivialKartAndroidGamepadInfo& Info : CachedAndroidGamepads) + { + if (!KnownAndroidDeviceStyles.Contains(Info.AndroidDeviceId)) + { + KnownAndroidDeviceStyles.Add(Info.AndroidDeviceId, Info.Style); + PendingHotplugStyles.Add(Info.Style); + } + } + + const ETrivialKartGamepadStyle AllStyles[] = { + ETrivialKartGamepadStyle::PlayStation, + ETrivialKartGamepadStyle::NintendoSwitch, + ETrivialKartGamepadStyle::GenericXbox + }; + for (ETrivialKartGamepadStyle Style : AllStyles) + { + const int32 ConnectedCount = CountConnectedAndroidStyle(Style); + int32 ConfirmedCount = 0; + for (const TPair& Pair : ConfirmedUnrealDeviceStyles) + { + if (Pair.Value == Style) + { + ++ConfirmedCount; + } + } + if (ConfirmedCount > ConnectedCount) + { + TArray> ExcessDevices; + for (int32 Pass = 0; Pass < 2 && ExcessDevices.Num() < (ConfirmedCount - ConnectedCount); ++Pass) + { + for (const TPair& Pair : ConfirmedUnrealDeviceStyles) + { + if (Pair.Value != Style) + { + continue; + } + // Pass 0 preserves LastActiveGamepadDeviceId so turning off an idle 2nd identical controller never resets the active one + if (Pass == 0 && Pair.Key == LastActiveGamepadDeviceId) + { + continue; + } + ExcessDevices.AddUnique(Pair.Key); + if (ExcessDevices.Num() >= (ConfirmedCount - ConnectedCount)) + { + break; + } + } + } + for (FInputDeviceId ExcessDeviceId : ExcessDevices) + { + EvictUnrealGamepadDevice(ExcessDeviceId); + } + } + } +#endif +} + +bool ATrivialKartPlayerController::TryClassifyGamepadName(const FString& ControllerName, ETrivialKartGamepadStyle& OutStyle) const +{ + FString Trimmed = ControllerName; + Trimmed.TrimStartAndEndInline(); + if (Trimmed.IsEmpty() || Trimmed.Equals(TEXT("None"), ESearchCase::IgnoreCase)) + { + return false; + } + +#if PLATFORM_ANDROID + // In UE5 FAndroidInputInterface, Microsoft (0x045e) and Sony (0x054c) map to explicit names while + // Nintendo Switch Pro / Joy-Con (0x057e) frequently reports "Generic". Cross-reference non-MS/Sony VendorIds. + if (Trimmed.Equals(TEXT("Generic"), ESearchCase::IgnoreCase)) + { + bool bFoundNonMsSony = false; + bool bUniformNonMsSony = true; + ETrivialKartGamepadStyle CandidateStyle = ETrivialKartGamepadStyle::GenericXbox; + for (const FTrivialKartAndroidGamepadInfo& Info : CachedAndroidGamepads) + { + if (Info.VendorId != 0x045e && Info.VendorId != 0x054c) + { + if (!bFoundNonMsSony) + { + bFoundNonMsSony = true; + CandidateStyle = Info.Style; + } + else if (Info.Style != CandidateStyle) + { + bUniformNonMsSony = false; + break; + } + } + } + if (bFoundNonMsSony && bUniformNonMsSony) + { + OutStyle = CandidateStyle; + return true; + } + return false; + } + + // 1. Exact case-insensitive match against JNI InputDevice.getName() entries (backed by hardware VendorId) + bool bFoundExactName = false; + bool bUniformExactStyle = true; + ETrivialKartGamepadStyle ExactStyle = ETrivialKartGamepadStyle::GenericXbox; + for (const FTrivialKartAndroidGamepadInfo& Info : CachedAndroidGamepads) + { + if (!Info.DeviceName.IsEmpty() && Info.DeviceName.Equals(Trimmed, ESearchCase::IgnoreCase)) + { + if (!bFoundExactName) + { + bFoundExactName = true; + ExactStyle = Info.Style; + } + else if (Info.Style != ExactStyle) + { + bUniformExactStyle = false; + break; + } + } + } + if (bFoundExactName) + { + if (bUniformExactStyle) + { + OutStyle = ExactStyle; + return true; + } + return false; + } +#else + if (Trimmed.Equals(TEXT("Generic"), ESearchCase::IgnoreCase)) + { + return false; + } +#endif + + // 2. Explicit controller brand / model tokens (shared across Android & Desktop) + if (Trimmed.Contains(TEXT("Xbox"), ESearchCase::IgnoreCase) || + Trimmed.Contains(TEXT("X-Box"), ESearchCase::IgnoreCase) || + Trimmed.Contains(TEXT("XInput"), ESearchCase::IgnoreCase) || + Trimmed.Contains(TEXT("Microsoft"), ESearchCase::IgnoreCase)) + { + OutStyle = ETrivialKartGamepadStyle::GenericXbox; + return true; + } + if (Trimmed.Contains(TEXT("DualSense"), ESearchCase::IgnoreCase) || + Trimmed.Contains(TEXT("DualShock"), ESearchCase::IgnoreCase) || + Trimmed.Contains(TEXT("PlayStation"), ESearchCase::IgnoreCase) || + Trimmed.Contains(TEXT("Sony"), ESearchCase::IgnoreCase) || + Trimmed.Contains(TEXT("PS4"), ESearchCase::IgnoreCase) || + Trimmed.Contains(TEXT("PS5"), ESearchCase::IgnoreCase)) + { + OutStyle = ETrivialKartGamepadStyle::PlayStation; + return true; + } + if (Trimmed.Contains(TEXT("Nintendo"), ESearchCase::IgnoreCase) || + Trimmed.Contains(TEXT("Switch"), ESearchCase::IgnoreCase) || + Trimmed.Contains(TEXT("Joy-Con"), ESearchCase::IgnoreCase) || + Trimmed.Contains(TEXT("JoyCon"), ESearchCase::IgnoreCase) || + Trimmed.Contains(TEXT("Pro Controller"), ESearchCase::IgnoreCase)) + { + OutStyle = ETrivialKartGamepadStyle::NintendoSwitch; + return true; + } + +#if PLATFORM_ANDROID + if (Trimmed.Equals(TEXT("Wireless Controller"), ESearchCase::IgnoreCase) && + HasConnectedAndroidStyle(ETrivialKartGamepadStyle::PlayStation)) + { + OutStyle = ETrivialKartGamepadStyle::PlayStation; + return true; + } + + // 3. Substring containment against JNI InputDevice.getName() entries + if (Trimmed.Len() >= 4) + { + bool bFoundSub = false; + bool bUniformSubStyle = true; + ETrivialKartGamepadStyle SubStyle = ETrivialKartGamepadStyle::GenericXbox; + for (const FTrivialKartAndroidGamepadInfo& Info : CachedAndroidGamepads) + { + if (Info.DeviceName.Len() >= 4 && + (Info.DeviceName.Contains(Trimmed, ESearchCase::IgnoreCase) || + Trimmed.Contains(Info.DeviceName, ESearchCase::IgnoreCase))) + { + if (!bFoundSub) + { + bFoundSub = true; + SubStyle = Info.Style; + } + else if (Info.Style != SubStyle) + { + bUniformSubStyle = false; + break; + } + } + } + if (bFoundSub && bUniformSubStyle) + { + OutStyle = SubStyle; + return true; + } + } +#endif + return false; +} + +bool ATrivialKartPlayerController::TryResolveStyleFromUnrealControllerSlot( + FInputDeviceId SourceDeviceId, + ETrivialKartGamepadStyle& OutStyle) +{ +#if PLATFORM_ANDROID + if (!SourceDeviceId.IsValid()) + { + return false; + } + + auto IsValidSlotName = [](const FString& Name) -> bool + { + return !Name.IsEmpty() && !Name.Equals(TEXT("None"), ESearchCase::IgnoreCase); + }; + + FTrivialKartUnrealSlotBinding& Binding = UnrealDeviceSlotBindings.FindOrAdd(SourceDeviceId); + if (Binding.bEvaluated) + { + if (Binding.SlotIndex != INDEX_NONE && !Binding.SlotName.IsEmpty()) + { + ETrivialKartGamepadStyle CachedNamedStyle = ETrivialKartGamepadStyle::GenericXbox; + if (TryClassifyGamepadName(Binding.SlotName, CachedNamedStyle) && HasConnectedAndroidStyle(CachedNamedStyle)) + { + OutStyle = CachedNamedStyle; + return true; + } + } + return false; + } + + Binding.bEvaluated = true; + + // Query FAndroidInputInterface::DeviceMapping[0..7] names directly via GetGamepadControllerName. + // Note: Do NOT call IPlatformInputDeviceMapper::RemapControllerIdToPlatformUserAndDevice under + // input.DeviceMappingPolicy=3 (MapAllDevicesToPrimaryUser), which maps Idx=0 to PrimaryUser's primary + // device regardless of which physical controller occupies FAndroidInputInterface::DeviceMapping[0]. + // Instead, FAndroidInputInterface assigns DeviceMapping[0..7] and dispatches SendControllerEvents() in + // ascending slot order, and NotifyGamepadDeviceDiscovered runs on each controller's very first packet, + // so UnclaimedPopulatedSlots[0] pairs 1-to-1 with SourceDeviceId in exact arrival order. + FString SlotNames[8]; + for (int32 Idx = 0; Idx < 8; ++Idx) + { + SlotNames[Idx] = UKismetSystemLibrary::GetGamepadControllerName(Idx); + SlotNames[Idx].TrimStartAndEndInline(); + } + + if (Binding.SlotIndex != INDEX_NONE) + { + if (!IsValidSlotName(SlotNames[Binding.SlotIndex]) || + (!Binding.SlotName.IsEmpty() && !SlotNames[Binding.SlotIndex].Equals(Binding.SlotName, ESearchCase::CaseSensitive))) + { + ClaimedAndroidControllerSlots.Remove(Binding.SlotIndex); + Binding.SlotIndex = INDEX_NONE; + Binding.SlotName.Reset(); + } + } + + if (Binding.SlotIndex == INDEX_NONE) + { + TArray> UnclaimedPopulatedSlots; + for (int32 Idx = 0; Idx < 8; ++Idx) + { + if (IsValidSlotName(SlotNames[Idx]) && !ClaimedAndroidControllerSlots.Contains(Idx)) + { + UnclaimedPopulatedSlots.Add(Idx); + } + } + + if (UnclaimedPopulatedSlots.Num() == 1) + { + const int32 MatchedSlot = UnclaimedPopulatedSlots[0]; + Binding.SlotIndex = MatchedSlot; + Binding.SlotName = SlotNames[MatchedSlot]; + ClaimedAndroidControllerSlots.Add(MatchedSlot); + } + else if (UnclaimedPopulatedSlots.Num() > 1) + { + bool bAnyClassified = false; + bool bAllSameSlotStyle = true; + ETrivialKartGamepadStyle SharedStyle = ETrivialKartGamepadStyle::GenericXbox; + for (int32 CandidateSlot : UnclaimedPopulatedSlots) + { + ETrivialKartGamepadStyle SlotStyle = ETrivialKartGamepadStyle::GenericXbox; + if (!TryClassifyGamepadName(SlotNames[CandidateSlot], SlotStyle)) + { + bAllSameSlotStyle = false; + break; + } + if (!bAnyClassified) + { + bAnyClassified = true; + SharedStyle = SlotStyle; + } + else if (SlotStyle != SharedStyle) + { + bAllSameSlotStyle = false; + break; + } + } + if (bAnyClassified && bAllSameSlotStyle && HasConnectedAndroidStyle(SharedStyle)) + { + const int32 MatchedSlot = UnclaimedPopulatedSlots[0]; + Binding.SlotIndex = MatchedSlot; + Binding.SlotName = SlotNames[MatchedSlot]; + ClaimedAndroidControllerSlots.Add(MatchedSlot); + OutStyle = SharedStyle; + return true; + } + } + } + + if (Binding.SlotIndex != INDEX_NONE && !Binding.SlotName.IsEmpty()) + { + ETrivialKartGamepadStyle NamedStyle = ETrivialKartGamepadStyle::GenericXbox; + if (TryClassifyGamepadName(Binding.SlotName, NamedStyle) && HasConnectedAndroidStyle(NamedStyle)) + { + OutStyle = NamedStyle; + return true; + } + } + return false; +#else + (void)SourceDeviceId; + (void)OutStyle; + return false; +#endif +} + +ETrivialKartGamepadStyle ATrivialKartPlayerController::ResolveGamepadStyleForDevice(FInputDeviceId SourceDeviceId) +{ +#if PLATFORM_ANDROID + if (!bHasInitialAndroidSnapshot || CachedAndroidGamepads.IsEmpty()) + { + RefreshAndroidGamepadSnapshot(); + } + if (CachedAndroidGamepads.IsEmpty()) + { + return ETrivialKartGamepadStyle::GenericXbox; + } + + // Fast path: all currently connected gamepads share the same controller family + const ETrivialKartGamepadStyle FirstStyle = CachedAndroidGamepads[0].Style; + bool bAllSameStyle = true; + for (int32 i = 1; i < CachedAndroidGamepads.Num(); ++i) + { + if (CachedAndroidGamepads[i].Style != FirstStyle) + { + bAllSameStyle = false; + break; + } + } + if (bAllSameStyle) + { + if (SourceDeviceId.IsValid()) + { + ETrivialKartGamepadStyle IgnoredSlotStyle = FirstStyle; + TryResolveStyleFromUnrealControllerSlot(SourceDeviceId, IgnoredSlotStyle); + SeenUnrealGamepadDevices.Add(SourceDeviceId); + ConfirmedUnrealDeviceStyles.Add(SourceDeviceId, FirstStyle); + } + PendingHotplugStyles.Empty(); + return FirstStyle; + } + + if (!SourceDeviceId.IsValid()) + { + return FirstStyle; + } + + const bool bIsNewlySeenUnrealDevice = !SeenUnrealGamepadDevices.Contains(SourceDeviceId); + SeenUnrealGamepadDevices.Add(SourceDeviceId); + + const ETrivialKartDeviceTriggerSignature Sig = GamepadInputProcessor.IsValid() + ? GamepadInputProcessor->GetDeviceTriggerSignature(SourceDeviceId) + : ETrivialKartDeviceTriggerSignature::Unknown; + + // Ensure SourceDeviceId claims its newly populated FAndroidInputInterface slot even if confirmed via trigger signature + ETrivialKartGamepadStyle PreSlotStyle = ETrivialKartGamepadStyle::GenericXbox; + const bool bHasDirectSlotStyle = TryResolveStyleFromUnrealControllerSlot(SourceDeviceId, PreSlotStyle); + + // 1. Unambiguous physical hardware trigger signatures (evaluated first so hardware signatures always self-heal) + if (Sig == ETrivialKartDeviceTriggerSignature::PlayStationHalfRest && HasConnectedAndroidStyle(ETrivialKartGamepadStyle::PlayStation)) + { + if (bIsNewlySeenUnrealDevice) + { + PendingHotplugStyles.RemoveSingle(ETrivialKartGamepadStyle::PlayStation); + } + ConfirmedUnrealDeviceStyles.Add(SourceDeviceId, ETrivialKartGamepadStyle::PlayStation); + return ETrivialKartGamepadStyle::PlayStation; + } + if (Sig == ETrivialKartDeviceTriggerSignature::SwitchDigitalOnly && HasConnectedAndroidStyle(ETrivialKartGamepadStyle::NintendoSwitch)) + { + if (bIsNewlySeenUnrealDevice) + { + PendingHotplugStyles.RemoveSingle(ETrivialKartGamepadStyle::NintendoSwitch); + } + ConfirmedUnrealDeviceStyles.Add(SourceDeviceId, ETrivialKartGamepadStyle::NintendoSwitch); + return ETrivialKartGamepadStyle::NintendoSwitch; + } + + // 2. Previously confirmed hardware style (preserved across calibrated 0.0..1.0 trigger travel) + if (const ETrivialKartGamepadStyle* ExistingConfirmed = ConfirmedUnrealDeviceStyles.Find(SourceDeviceId)) + { + return *ExistingConfirmed; + } + + // 3. Direct per-slot hardware name lookup via FAndroidInputInterface (UKismetSystemLibrary::GetGamepadControllerName) + // cross-referenced against JNI VendorId (0x054c PlayStation, 0x057e Switch, 0x045e Xbox) + if (bHasDirectSlotStyle) + { + if (bIsNewlySeenUnrealDevice) + { + PendingHotplugStyles.RemoveSingle(PreSlotStyle); + } + ConfirmedUnrealDeviceStyles.Add(SourceDeviceId, PreSlotStyle); + return PreSlotStyle; + } + + // 4. Hot-plugged device correlation (supports single-device or uniform multi-subdevice pairs like Joy-Con L+R) + if (bIsNewlySeenUnrealDevice) + { + ETrivialKartGamepadStyle HotplugStyle = ETrivialKartGamepadStyle::GenericXbox; + if (TryPopUniformPendingHotplugStyle(HotplugStyle)) + { + ConfirmedUnrealDeviceStyles.Add(SourceDeviceId, HotplugStyle); + return HotplugStyle; + } + } + + // 5. Multiset elimination against already-confirmed FInputDeviceIds + AnalogTriggerCapable (which rules out Switch) + auto CountRemainingStyle = [this, SourceDeviceId](ETrivialKartGamepadStyle Style) -> int32 + { + int32 Count = CountConnectedAndroidStyle(Style); + for (const TPair& Pair : ConfirmedUnrealDeviceStyles) + { + if (Pair.Key != SourceDeviceId && Pair.Value == Style && Count > 0) + { + --Count; + } + } + return Count; + }; + + const int32 RemPS = CountRemainingStyle(ETrivialKartGamepadStyle::PlayStation); + const int32 RemSwitch = (Sig == ETrivialKartDeviceTriggerSignature::AnalogTriggerCapable) + ? 0 + : CountRemainingStyle(ETrivialKartGamepadStyle::NintendoSwitch); + const int32 RemXbox = CountRemainingStyle(ETrivialKartGamepadStyle::GenericXbox); + const int32 DistinctRemaining = (RemPS > 0 ? 1 : 0) + (RemSwitch > 0 ? 1 : 0) + (RemXbox > 0 ? 1 : 0); + if (DistinctRemaining == 1) + { + const ETrivialKartGamepadStyle DeducedStyle = (RemPS > 0) + ? ETrivialKartGamepadStyle::PlayStation + : ((RemSwitch > 0) ? ETrivialKartGamepadStyle::NintendoSwitch : ETrivialKartGamepadStyle::GenericXbox); + ConfirmedUnrealDeviceStyles.Add(SourceDeviceId, DeducedStyle); + return DeducedStyle; + } + + // 6. Provisional fallback restricted strictly to unclaimed connected styles (never returning a style already + // confirmed on another FInputDeviceId). + if (RemXbox > 0) + { + return ETrivialKartGamepadStyle::GenericXbox; + } + if (RemSwitch > 0) + { + return ETrivialKartGamepadStyle::NintendoSwitch; + } + if (RemPS > 0) + { + return ETrivialKartGamepadStyle::PlayStation; + } + return ETrivialKartGamepadStyle::GenericXbox; +#else + if (SourceDeviceId.IsValid()) + { + if (const ETrivialKartGamepadStyle* CachedStyle = ConfirmedUnrealDeviceStyles.Find(SourceDeviceId)) + { + return *CachedStyle; + } + } + + if (UInputDeviceSubsystem* InputDeviceSubsystem = UInputDeviceSubsystem::Get()) + { + FHardwareDeviceIdentifier HardwareDevice = SourceDeviceId.IsValid() + ? InputDeviceSubsystem->GetInputDeviceHardwareIdentifier(SourceDeviceId) + : FHardwareDeviceIdentifier(); + const bool bResolvedSpecificDevice = !HardwareDevice.HardwareDeviceIdentifier.IsNone(); + if (!bResolvedSpecificDevice) + { + HardwareDevice = InputDeviceSubsystem->GetMostRecentlyUsedHardwareDevice(GetPlatformUserId()); + } + + ETrivialKartGamepadStyle ResolvedStyle = ETrivialKartGamepadStyle::GenericXbox; + TryClassifyGamepadName(HardwareDevice.HardwareDeviceIdentifier.ToString(), ResolvedStyle); + + if (SourceDeviceId.IsValid() && bResolvedSpecificDevice) + { + ConfirmedUnrealDeviceStyles.Add(SourceDeviceId, ResolvedStyle); + } + return ResolvedStyle; + } + return ETrivialKartGamepadStyle::GenericXbox; +#endif +} + +void ATrivialKartPlayerController::RefreshGamepadStyleForDevice(FInputDeviceId SourceDeviceId, bool bBroadcastIfChanged) +{ + const ETrivialKartGamepadStyle NewStyle = ResolveGamepadStyleForDevice(SourceDeviceId); + if (ActiveGamepadStyle != NewStyle) + { + ActiveGamepadStyle = NewStyle; + if (bBroadcastIfChanged && ActiveInputMode == ETrivialKartInputMode::Gamepad) + { + OnInputModeUpdated.Broadcast(ActiveInputMode); + } + } +} + void ATrivialKartPlayerController::RemapAllDevicesToPrimaryUser() const { #if !WITH_EDITOR @@ -699,11 +1724,24 @@ void ATrivialKartPlayerController::RemapAllDevicesToPrimaryUser() const void ATrivialKartPlayerController::SyncGamepadAttachmentState() { RemapAllDevicesToPrimaryUser(); + RefreshAndroidGamepadSnapshot(); const bool bNowAttached = QueryAnyGamepadAttached(); const bool bJustAttachedFirstGamepad = (!bWasGamepadAttached && bNowAttached); bWasGamepadAttached = bNowAttached; + if (bNowAttached) + { + if (LastActiveGamepadDeviceId.IsValid()) + { + RefreshGamepadStyleForDevice(LastActiveGamepadDeviceId, true); + } + else if (bJustAttachedFirstGamepad || !HasConnectedAndroidStyle(ActiveGamepadStyle)) + { + RefreshGamepadStyleForDevice(INPUTDEVICEID_NONE, true); + } + } + if (bJustAttachedFirstGamepad) { if ((FPlatformTime::Seconds() - LastNonGamepadInputTimeSeconds) > 0.25) @@ -711,17 +1749,33 @@ void ATrivialKartPlayerController::SyncGamepadAttachmentState() SetActiveInputMode(ETrivialKartInputMode::Gamepad); } } - else if (!bNowAttached && ActiveInputMode == ETrivialKartInputMode::Gamepad) - { + else if (!bNowAttached) + { + LastActiveGamepadDeviceId = INPUTDEVICEID_NONE; + SeenUnrealGamepadDevices.Empty(); + ConfirmedUnrealDeviceStyles.Empty(); + UnrealDeviceSlotBindings.Empty(); + ClaimedAndroidControllerSlots.Empty(); + PendingHotplugStyles.Empty(); + KnownAndroidDeviceStyles.Empty(); + CachedAndroidGamepads.Empty(); + ActiveGamepadStyle = ETrivialKartGamepadStyle::GenericXbox; if (GamepadInputProcessor.IsValid()) { - GamepadInputProcessor->ResetState(); + GamepadInputProcessor->ResetDeviceCapabilities(); } + if (ActiveInputMode == ETrivialKartInputMode::Gamepad) + { + if (GamepadInputProcessor.IsValid()) + { + GamepadInputProcessor->ResetState(); + } #if PLATFORM_ANDROID - SetActiveInputMode(ETrivialKartInputMode::Touch); + SetActiveInputMode(ETrivialKartInputMode::Touch); #else - SetActiveInputMode(PreviousNonGamepadMode); + SetActiveInputMode(PreviousNonGamepadMode); #endif + } } } @@ -743,6 +1797,16 @@ void ATrivialKartPlayerController::OnInputDeviceConnectionChange( return; } + if (NewConnectionState == EInputDeviceConnectionState::Disconnected && InputDeviceId.IsValid()) + { + EvictUnrealGamepadDevice(InputDeviceId); + } + else if (NewConnectionState == EInputDeviceConnectionState::Connected && InputDeviceId.IsValid()) + { + RefreshAndroidGamepadSnapshot(); + InvalidatePendingUnrealSlotEvaluations(); + } + RemapAllDevicesToPrimaryUser(); if (!DeviceCheckTickerHandle.IsValid()) diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/GameInstances/TrivialKartGameInstance.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/GameInstances/TrivialKartGameInstance.cpp index 0ba1860f..5dcfdd5c 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/GameInstances/TrivialKartGameInstance.cpp +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/GameInstances/TrivialKartGameInstance.cpp @@ -23,9 +23,9 @@ #include "Interfaces/OnlineIdentityInterface.h" #include "Interfaces/OnlinePurchaseInterface.h" #include "Kismet/GameplayStatics.h" +#include "Misc/ConfigCacheIni.h" #include "Objects/TrivialKartSaveGame.h" #include "Actors/TrivialKartHUD.h" -#include "GameFramework/PlayerState.h" #include "Actors/KartPawn.h" DEFINE_LOG_CATEGORY(LogTemplateGameInstance); @@ -63,14 +63,41 @@ void UTrivialKartGameInstance::Shutdown() CloudInterface->ClearOnWriteUserFileCompleteDelegate_Handle(WriteSaveHandle); } FCoreDelegates::ApplicationHasEnteredForegroundDelegate.RemoveAll(this); + ClearCloudSyncWatchdog(); Super::Shutdown(); } void UTrivialKartGameInstance::InitiateAutoLogin() { - if (const IOnlineIdentityPtr IdentityInterface = Online::GetIdentityInterface(GetWorld())) + bool bPlayGamesConfigured = true; +#if PLATFORM_ANDROID + if (GConfig) + { + FString GamesAppID; + FString PlayGamesClientId; + GConfig->GetString(TEXT("/Script/AndroidRuntimeSettings.AndroidRuntimeSettings"), TEXT("GamesAppID"), GamesAppID, GEngineIni); + GConfig->GetString(TEXT("/Script/AndroidRuntimeSettings.AndroidRuntimeSettings"), TEXT("PlayGamesClientId"), PlayGamesClientId, GEngineIni); + bPlayGamesConfigured = !GamesAppID.TrimStartAndEnd().IsEmpty() || !PlayGamesClientId.TrimStartAndEnd().IsEmpty(); + } +#endif + + const IOnlineIdentityPtr IdentityInterface = Online::GetIdentityInterface(GetWorld()); + const IOnlineUserCloudPtr CloudInterface = Online::GetUserCloudInterface(GetWorld()); + if (IdentityInterface.IsValid() && bPlayGamesConfigured) { - IdentityInterface->AutoLogin(0); + if (CloudInterface.IsValid()) + { + bCloudSyncInFlight = true; + ArmCloudSyncWatchdog(); + } + if (!IdentityInterface->AutoLogin(0)) + { + DismissLoadingScreen(); + } + } + else + { + DismissLoadingScreen(); } } @@ -99,19 +126,23 @@ void UTrivialKartGameInstance::AddAchievementProgress(const float Progress, cons if (const IOnlineIdentityPtr IdentityInterface = Online::GetIdentityInterface(GetWorld()); IdentityInterface.IsValid()) { + const FUniqueNetIdPtr UserId = IdentityInterface->GetUniquePlayerId(0); + if (IdentityInterface->GetLoginStatus(0) != ELoginStatus::LoggedIn || !UserId.IsValid()) + { + return; + } if (const IOnlineAchievementsPtr AchievementsInterface = Online::GetAchievementsInterface(GetWorld()); AchievementsInterface.IsValid()) { FOnlineAchievement CurrentAchievement; - AchievementsInterface->GetCachedAchievement(*IdentityInterface->GetUniquePlayerId(0), AchievementName, CurrentAchievement); + AchievementsInterface->GetCachedAchievement(*UserId, AchievementName, CurrentAchievement); if (CurrentAchievement.Progress < 100.0) { const float CurrentProgress = CurrentAchievement.Progress + Progress; const FOnlineAchievementsWritePtr AchievementPtr = MakeShareable(new FOnlineAchievementsWrite()); AchievementPtr->SetFloatStat(AchievementName, CurrentProgress); FOnlineAchievementsWriteRef AchievementRef = AchievementPtr.ToSharedRef(); - AchievementsInterface->WriteAchievements(*IdentityInterface->GetUniquePlayerId(0), - AchievementRef); + AchievementsInterface->WriteAchievements(*UserId, AchievementRef); } } } @@ -123,6 +154,11 @@ void UTrivialKartGameInstance::StartPurchasing(const FUniqueOfferId& OfferID, co { if (const IOnlineIdentityPtr IdentityInterface = Online::GetIdentityInterface(GetWorld())) { + const FUniqueNetIdPtr UserId = IdentityInterface->GetUniquePlayerId(0); + if (IdentityInterface->GetLoginStatus(0) != ELoginStatus::LoggedIn || !UserId.IsValid()) + { + return; + } if (const IOnlineStoreV2Ptr StoreV2Interface = Subsystem->GetStoreV2Interface()) { if (const TSharedPtr CurrentOrder = StoreV2Interface->GetOffer(OfferID); @@ -131,7 +167,7 @@ void UTrivialKartGameInstance::StartPurchasing(const FUniqueOfferId& OfferID, co if (const IOnlinePurchasePtr PurchaseInterface = Online::GetPurchaseInterface(GetWorld()); PurchaseInterface.IsValid()) { - if (PurchaseInterface->IsAllowedToPurchase(*IdentityInterface->GetUniquePlayerId(0))) + if (PurchaseInterface->IsAllowedToPurchase(*UserId)) { FPurchaseCheckoutRequest CheckoutRequest; @@ -142,7 +178,7 @@ void UTrivialKartGameInstance::StartPurchasing(const FUniqueOfferId& OfferID, co Quantity, bIsConsumable ); - PurchaseInterface->Checkout(*IdentityInterface->GetUniquePlayerId(0), + PurchaseInterface->Checkout(*UserId, CheckoutRequest, FOnPurchaseCheckoutComplete::CreateWeakLambda(this, [this, IdentityInterface, OfferID, Quantity] @@ -155,7 +191,12 @@ void UTrivialKartGameInstance::StartPurchasing(const FUniqueOfferId& OfferID, co OnPurchaseReceived.Broadcast(OfferID, Quantity); } // The Purchase Token is passed as the ReceiptId to tell the platform which purchase to finalize (consume/acknowledge). - Online::GetPurchaseInterface(GetWorld())->FinalizePurchase(*IdentityInterface->GetUniquePlayerId(0), PurchaseReceipt->TransactionId); + const FUniqueNetIdPtr ActiveUserId = IdentityInterface.IsValid() ? IdentityInterface->GetUniquePlayerId(0) : nullptr; + const IOnlinePurchasePtr ActivePurchaseInterface = Online::GetPurchaseInterface(GetWorld()); + if (ActiveUserId.IsValid() && ActivePurchaseInterface.IsValid()) + { + ActivePurchaseInterface->FinalizePurchase(*ActiveUserId, PurchaseReceipt->TransactionId); + } })); } } @@ -227,19 +268,28 @@ void UTrivialKartGameInstance::SaveGame(UTrivialKartSaveGame* SaveData) if (const IOnlineIdentityPtr IdentityInterface = Online::GetIdentityInterface(GetWorld())) { - if (const IOnlineUserCloudPtr CloudInterface = Online::GetUserCloudInterface(GetWorld())) + const FUniqueNetIdPtr UserId = IdentityInterface->GetUniquePlayerId(0); + if (IdentityInterface->GetLoginStatus(0) == ELoginStatus::LoggedIn && UserId.IsValid()) { - if (TWeakObjectPtr PlayerController = UGameplayStatics::GetPlayerController(GetWorld(), 0); PlayerController.IsValid()) + if (const IOnlineUserCloudPtr CloudInterface = Online::GetUserCloudInterface(GetWorld())) { - if (TWeakObjectPtr PlayerHUD = Cast(PlayerController->GetHUD()); PlayerHUD.IsValid()) + bCloudSyncInFlight = true; + ArmCloudSyncWatchdog(); + if (TWeakObjectPtr PlayerController = UGameplayStatics::GetPlayerController(GetWorld(), 0); PlayerController.IsValid()) { - PlayerHUD->AddWidgetToScreen(EWidgetType::Loading, 10); + if (TWeakObjectPtr PlayerHUD = Cast(PlayerController->GetHUD()); PlayerHUD.IsValid()) + { + PlayerHUD->AddWidgetToScreen(EWidgetType::Loading, 10); + } } - } - TArray ObjectBytes; - UGameplayStatics::SaveGameToMemory(SaveData, ObjectBytes); + TArray ObjectBytes; + UGameplayStatics::SaveGameToMemory(SaveData, ObjectBytes); - CloudInterface->WriteUserFile(*IdentityInterface->GetUniquePlayerId(0), "TrivialKartCloudSave", ObjectBytes); + if (!CloudInterface->WriteUserFile(*UserId, "TrivialKartCloudSave", ObjectBytes)) + { + DismissLoadingScreen(); + } + } } } } @@ -249,33 +299,45 @@ void UTrivialKartGameInstance::OnLoginCompleted(int32 LocalUserNum, bool bWasSuc { UE_LOG(LogTemplateGameInstance, Log, TEXT("Local User: %d of Unique ID: %s has logged in with Status: %s"), LocalUserNum, *UserId.ToDebugString(), bWasSuccessful ? TEXT("Success") : *Error); + bool bStartedCloudRead = false; if (bWasSuccessful) { if (const IOnlineIdentityPtr IdentityInterface = Online::GetIdentityInterface(GetWorld())) { - if (const IOnlineAchievementsPtr AchievementsInterface = - Online::GetAchievementsInterface(GetWorld())) + if (const FUniqueNetIdPtr PlayerId = IdentityInterface->GetUniquePlayerId(0); PlayerId.IsValid()) { - AchievementsInterface->QueryAchievements(*IdentityInterface->GetUniquePlayerId(0), - FOnQueryAchievementsCompleteDelegate::CreateUObject(this, - &UTrivialKartGameInstance::OnQueryAchievementsCompleted)); - } - if (const IOnlineSubsystem* Subsystem = Online::GetSubsystem(GetWorld())) - { - if (const IOnlineStoreV2Ptr StoreInterface = Subsystem->GetStoreV2Interface()) + if (const IOnlineAchievementsPtr AchievementsInterface = + Online::GetAchievementsInterface(GetWorld())) { - StoreInterface->QueryOffersById(*IdentityInterface->GetUniquePlayerId(0), StoreListItemIDs, - FOnQueryOnlineStoreOffersComplete::CreateUObject(this, &UTrivialKartGameInstance::OnQueryOnlineStoreOfferCompleted)); + AchievementsInterface->QueryAchievements(*PlayerId, + FOnQueryAchievementsCompleteDelegate::CreateUObject(this, + &UTrivialKartGameInstance::OnQueryAchievementsCompleted)); + } + if (const IOnlineSubsystem* Subsystem = Online::GetSubsystem(GetWorld())) + { + if (const IOnlineStoreV2Ptr StoreInterface = Subsystem->GetStoreV2Interface()) + { + StoreInterface->QueryOffersById(*PlayerId, StoreListItemIDs, + FOnQueryOnlineStoreOffersComplete::CreateUObject(this, &UTrivialKartGameInstance::OnQueryOnlineStoreOfferCompleted)); + } + } + if (const IOnlineUserCloudPtr CloudInterface = Online::GetUserCloudInterface(GetWorld())) + { + bStartedCloudRead = CloudInterface->ReadUserFile(*PlayerId, "TrivialKartCloudSave"); } - } - if (const IOnlineUserCloudPtr CloudInterface = Online::GetUserCloudInterface(GetWorld())) - { - CloudInterface->ReadUserFile(*IdentityInterface->GetUniquePlayerId(0), "TrivialKartCloudSave"); } } // Check unacknowledged purchases on start or foreground CheckPendingPurchases(); } + if (bStartedCloudRead) + { + ArmCloudSyncWatchdog(); + } + else + { + DismissLoadingScreen(); + } } void UTrivialKartGameInstance::OnQueryAchievementsCompleted(const FUniqueNetId& UniqueNetId, bool bWasSuccessful) @@ -326,34 +388,73 @@ void UTrivialKartGameInstance::OnCloudReadComplete(bool bWasSuccessful, const FU { CurrentPawn->SwitchCar(SaveGameInstance->ActiveCarType); } - if (TWeakObjectPtr PlayerHUD = Cast(PlayerController->GetHUD()); PlayerHUD.IsValid()) - { - PlayerHUD->RemoveWidgetFromScreen(EWidgetType::Loading); - } } + DismissLoadingScreen(); UE_LOG(LogTemplateGameInstance, Log, TEXT("Cloud Save %s for file: %s"), bWasSuccessful ? *FString("was successful") : *FString("has failed"), *FileName); } void UTrivialKartGameInstance::OnCloudWriteComplete(bool bWasSuccessful, const FUniqueNetId& UserId, const FString& FileName) { + bool bStartedCloudRead = false; if (bWasSuccessful) { if (const IOnlineIdentityPtr IdentityInterface = Online::GetIdentityInterface(GetWorld())) { - if (const IOnlineUserCloudPtr CloudInterface = Online::GetUserCloudInterface(GetWorld())) + if (const FUniqueNetIdPtr PlayerId = IdentityInterface->GetUniquePlayerId(0); PlayerId.IsValid()) { - CloudInterface->ReadUserFile(*IdentityInterface->GetUniquePlayerId(0), "TrivialKartCloudSave"); + if (const IOnlineUserCloudPtr CloudInterface = Online::GetUserCloudInterface(GetWorld())) + { + bStartedCloudRead = CloudInterface->ReadUserFile(*PlayerId, "TrivialKartCloudSave"); + } } } } + if (bStartedCloudRead) + { + ArmCloudSyncWatchdog(); + } else { - if (TWeakObjectPtr PlayerController = UGameplayStatics::GetPlayerController(GetWorld(), 0); PlayerController.IsValid()) + DismissLoadingScreen(); + } +} + +void UTrivialKartGameInstance::ArmCloudSyncWatchdog() +{ + ClearCloudSyncWatchdog(); + TWeakObjectPtr WeakThis(this); + CloudSyncTimeoutHandle = FTSTicker::GetCoreTicker().AddTicker( + FTickerDelegate::CreateLambda([WeakThis](float) { - if (TWeakObjectPtr PlayerHUD = Cast(PlayerController->GetHUD()); PlayerHUD.IsValid()) + if (UTrivialKartGameInstance* StrongThis = WeakThis.Get()) { - PlayerHUD->RemoveWidgetFromScreen(EWidgetType::Loading); + StrongThis->CloudSyncTimeoutHandle.Reset(); + UE_LOG(LogTemplateGameInstance, Warning, TEXT("Cloud sync timed out; dismissing Loading screen.")); + StrongThis->DismissLoadingScreen(); } + return false; + }), + 10.0f); +} + +void UTrivialKartGameInstance::ClearCloudSyncWatchdog() +{ + if (CloudSyncTimeoutHandle.IsValid()) + { + FTSTicker::GetCoreTicker().RemoveTicker(CloudSyncTimeoutHandle); + CloudSyncTimeoutHandle.Reset(); + } +} + +void UTrivialKartGameInstance::DismissLoadingScreen() +{ + ClearCloudSyncWatchdog(); + bCloudSyncInFlight = false; + if (TWeakObjectPtr PlayerController = UGameplayStatics::GetPlayerController(GetWorld(), 0); PlayerController.IsValid()) + { + if (TWeakObjectPtr PlayerHUD = Cast(PlayerController->GetHUD()); PlayerHUD.IsValid()) + { + PlayerHUD->RemoveWidgetFromScreen(EWidgetType::Loading); } } } diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Infos/TrivialKartPlayerState.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Infos/TrivialKartPlayerState.cpp index b7d791be..1339f205 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Infos/TrivialKartPlayerState.cpp +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Infos/TrivialKartPlayerState.cpp @@ -105,6 +105,28 @@ void ATrivialKartPlayerState::AddCarToInventory(const FString& CarID) } } +bool ATrivialKartPlayerState::PurchaseCarWithCoins(const FString& CarID, const int CoinsUsed) +{ + if (CarID.IsEmpty() || CarsOwned.Contains(CarID) || CoinCount < CoinsUsed) + { + return false; + } + CarsOwned.Add(CarID); + CoinCount = FMath::Max(0, CoinCount - CoinsUsed); + OnCoinUpdated.ExecuteIfBound(CoinCount); + if (TWeakObjectPtr Instance = Cast(GetGameInstance()); + Instance.IsValid()) + { + if (TWeakObjectPtr Save = Instance->LoadGame(); Save.IsValid()) + { + Save->CarsOwned = CarsOwned; + Save->CurrentCoins = CoinCount; + Instance->SaveGame(Save.Get()); + } + } + return true; +} + float ATrivialKartPlayerState::GetFuel() const { return Fuel; diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/GarageWidget.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/GarageWidget.cpp index cee0e8e1..8aed7518 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/GarageWidget.cpp +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/GarageWidget.cpp @@ -14,98 +14,21 @@ * limitations under the License. */ - #include "Widgets/GarageWidget.h" -#include "Actors/TrivialKartHUD.h" -#include "Blueprint/WidgetTree.h" -#include "Components/Border.h" -#include "Components/Button.h" #include "Components/CheckBox.h" -#include "Components/HorizontalBox.h" -#include "Components/Image.h" -#include "Components/Overlay.h" -#include "Components/OverlaySlot.h" -#include "Components/PanelWidget.h" -#include "Components/ScrollBox.h" -#include "Components/TextBlock.h" -#include "Components/VerticalBox.h" -#include "Components/WidgetSwitcher.h" #include "GameInstances/TrivialKartGameInstance.h" #include "Objects/TrivialKartSaveGame.h" #include "Widgets/SelectableItem.h" -static UBorder* EnsureGarageTabHighlightBorder(UWidgetTree* WidgetTree, UCheckBox* CB) +void UGarageWidget::RegisterTabCheckBoxes(TArray& OutCheckBoxes) { - UOverlay* ParentOverlay = CB ? Cast(CB->GetParent()) : nullptr; - if (!WidgetTree || !ParentOverlay) - { - return nullptr; - } - - UBorder* Border = WidgetTree->ConstructWidget(UBorder::StaticClass()); - Border->SetVisibility(ESlateVisibility::Collapsed); - Border->SetPadding(FMargin(0.0f)); - if (UOverlaySlot* OverlaySlot = ParentOverlay->AddChildToOverlay(Border)) - { - OverlaySlot->SetHorizontalAlignment(HAlign_Fill); - OverlaySlot->SetVerticalAlignment(VAlign_Fill); - } - return Border; + OutCheckBoxes.Add(KartCheckBox); + OutCheckBoxes.Add(LevelCheckBox); } -void UGarageWidget::NativeConstruct() +void UGarageWidget::BindTabCheckBoxEvents() { - Super::NativeConstruct(); - - // Keep the modal root hit-testable so empty modal space blocks clicks from piercing into FSceneViewport - SetVisibility(ESlateVisibility::Visible); - - if (WidgetTree) - { - UWidget* TreeRoot = WidgetTree->RootWidget; - WidgetTree->ForEachWidget([TreeRoot](UWidget* Widget) - { - if (!Widget || Widget == TreeRoot || Widget->GetVisibility() != ESlateVisibility::Visible) - { - return; - } - if (Cast(Widget) || Cast(Widget)) - { - Widget->SetVisibility(ESlateVisibility::HitTestInvisible); - } - else if (Cast(Widget) || Cast(Widget) || Cast(Widget)) - { - Widget->SetVisibility(ESlateVisibility::SelfHitTestInvisible); - } - }); - } - - if (BackButton) - { - if (!bBackStyleCached) - { - OriginalBackButtonStyle = BackButton->GetStyle(); - OriginalBackButtonBgColor = BackButton->GetBackgroundColor(); - bBackStyleCached = true; - } - BackButton->OnClicked.AddUniqueDynamic(this, &UGarageWidget::OnBackButtonClicked); - BackButton->OnReleased.AddUniqueDynamic(this, &UGarageWidget::OnBackButtonReleased); - } - - CheckBoxes.Empty(); - CheckBoxes.Add(KartCheckBox); - CheckBoxes.Add(LevelCheckBox); - - if (TabHighlightBorders.Num() != CheckBoxes.Num()) - { - TabHighlightBorders.Empty(); - for (UCheckBox* CB : CheckBoxes) - { - TabHighlightBorders.Add(EnsureGarageTabHighlightBorder(WidgetTree, CB)); - } - } - if (KartCheckBox) { KartCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UGarageWidget::OnKartBoxStateChanged); @@ -114,29 +37,10 @@ void UGarageWidget::NativeConstruct() { LevelCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UGarageWidget::OnLevelBoxStateChange); } - - if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) - { - PC->OnInputModeUpdated.RemoveAll(this); - PC->OnInputModeUpdated.AddUObject(this, &UGarageWidget::OnInputModeChanged); - } - - GamepadPressedItem.Reset(); - HoveredItem.Reset(); - bBackButtonPressed = false; - RefreshAllItemsOwnership(); - ActiveTabIndex = ContentSwitcher ? ContentSwitcher->GetActiveWidgetIndex() : 0; - FocusedItemIndex = (ActiveTabIndex == 0) ? FindActiveCarItemIndex() : 0; - RefreshGamepadFocus(IsNavigationVisualActive()); } -void UGarageWidget::NativeDestruct() +void UGarageWidget::UnbindTabCheckBoxEvents() { - if (BackButton) - { - BackButton->OnClicked.RemoveDynamic(this, &UGarageWidget::OnBackButtonClicked); - BackButton->OnReleased.RemoveDynamic(this, &UGarageWidget::OnBackButtonReleased); - } if (KartCheckBox) { KartCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UGarageWidget::OnKartBoxStateChanged); @@ -145,166 +49,24 @@ void UGarageWidget::NativeDestruct() { LevelCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UGarageWidget::OnLevelBoxStateChange); } - - if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) - { - PC->OnInputModeUpdated.RemoveAll(this); - } - - CheckBoxes.Empty(); - Super::NativeDestruct(); -} - -bool UGarageWidget::IsNavigationVisualActive() const -{ - if (const ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) - { - return PC->IsKeyNavigationActive(); - } - return false; -} - -void UGarageWidget::RestoreViewportFocus() const -{ - if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) - { - PC->RestoreFocusToGameViewport(); - } -} - -void UGarageWidget::OnInputModeChanged(ETrivialKartInputMode NewInputMode) -{ - if (!IsNavigationVisualActive()) - { - CancelPendingPress(); - } - RefreshGamepadFocus(false); -} - -void UGarageWidget::OnBackButtonReleased() -{ - RestoreViewportFocus(); -} - -void UGarageWidget::OnBackButtonClicked() -{ - if (TWeakObjectPtr PlayerController = GetOwningPlayer(); PlayerController.IsValid()) - { - if (const TWeakObjectPtr CurrentHUD = Cast(PlayerController->GetHUD()); - CurrentHUD.IsValid()) - { - CurrentHUD->AddWidgetToScreen(EWidgetType::PlayBoard); - CurrentHUD->RemoveWidgetFromScreen(EWidgetType::Garage); - } - } -} - -void UGarageWidget::SetCheckBoxState(bool bIsChecked, UCheckBox* CheckBox, int ActiveWidgetIndex) -{ - if (CheckBox == nullptr) - { - return; - } - CancelPendingPress(); - HoveredItem.Reset(); - FocusedItemIndex = -1; - if (bIsChecked) - { - ActiveTabIndex = ActiveWidgetIndex; - if (ContentSwitcher) - { - ContentSwitcher->SetActiveWidgetIndex(ActiveWidgetIndex); - } - for (auto CurrentCheckBox : CheckBoxes) - { - if (CurrentCheckBox && CurrentCheckBox != CheckBox) - { - CurrentCheckBox->SetCheckedState(ECheckBoxState::Unchecked); - } - } - } - else - { - CheckBox->SetCheckedState(ECheckBoxState::Checked); - } - RefreshAllItemsOwnership(); - RefreshGamepadFocus(false); - RestoreViewportFocus(); -} - -void UGarageWidget::SelectTabByIndex(int32 NewTabIndex) -{ - if (CheckBoxes.Num() == 0) - { - return; - } - ActiveTabIndex = (NewTabIndex + CheckBoxes.Num()) % CheckBoxes.Num(); - if (UCheckBox* TargetCheckBox = CheckBoxes[ActiveTabIndex]) - { - TargetCheckBox->SetCheckedState(ECheckBoxState::Checked); - SetCheckBoxState(true, TargetCheckBox, ActiveTabIndex); - } } -void UGarageWidget::RefreshAllItemsOwnership() const +int32 UGarageWidget::GetDefaultItemIndexForTab(int32 TabIndex, const TArray& ActiveItems) const { - TArray AllItems; - GatherSelectableItems(ContentSwitcher, AllItems, false); - for (USelectableItem* Item : AllItems) + if (TabIndex == 0) { - if (Item) + if (UTrivialKartGameInstance* Instance = Cast(GetGameInstance())) { - Item->RefreshOwnershipState(); - } - } -} - -void UGarageWidget::GatherSelectableItems(UWidget* RootWidget, TArray& OutItems, bool bOnlySelectable) const -{ - if (!RootWidget) - { - return; - } - if (USelectableItem* Item = Cast(RootWidget)) - { - if (!bOnlySelectable || Item->IsItemSelectable()) - { - OutItems.Add(Item); - } - return; - } - if (bOnlySelectable && !RootWidget->IsVisible()) - { - return; - } - if (UPanelWidget* Panel = Cast(RootWidget)) - { - for (int32 i = 0; i < Panel->GetChildrenCount(); ++i) - { - GatherSelectableItems(Panel->GetChildAt(i), OutItems, bOnlySelectable); - } - } -} - -int32 UGarageWidget::FindActiveCarItemIndex() const -{ - if (!ContentSwitcher) - { - return 0; - } - TArray ActiveItems; - GatherSelectableItems(ContentSwitcher->GetActiveWidget(), ActiveItems, true); - if (UTrivialKartGameInstance* Instance = Cast(GetGameInstance())) - { - if (UTrivialKartSaveGame* Save = Instance->LoadGame()) - { - if (!Save->ActiveCarType.IsEmpty()) + if (UTrivialKartSaveGame* Save = Instance->LoadGame()) { - for (int32 i = 0; i < ActiveItems.Num(); ++i) + if (!Save->ActiveCarType.IsEmpty()) { - if (ActiveItems[i] && ActiveItems[i]->GetCarType().Equals(Save->ActiveCarType, ESearchCase::IgnoreCase)) + for (int32 i = 0; i < ActiveItems.Num(); ++i) { - return i; + if (ActiveItems[i] && ActiveItems[i]->GetCarType().Equals(Save->ActiveCarType, ESearchCase::IgnoreCase)) + { + return i; + } } } } @@ -313,385 +75,6 @@ int32 UGarageWidget::FindActiveCarItemIndex() const return 0; } -void UGarageWidget::OnSelectableItemInteracted(USelectableItem* InteractedItem) -{ - HoveredItem = InteractedItem; - TArray ActiveItems; - if (ContentSwitcher) - { - GatherSelectableItems(ContentSwitcher->GetActiveWidget(), ActiveItems, true); - } - const int32 FoundIndex = ActiveItems.IndexOfByKey(InteractedItem); - if (FoundIndex != INDEX_NONE) - { - FocusedItemIndex = FoundIndex; - } - RefreshGamepadFocus(false); -} - -void UGarageWidget::OnSelectableItemUnhovered(USelectableItem* UnhoveredItem) -{ - if (HoveredItem.Get() == UnhoveredItem) - { - HoveredItem.Reset(); - if (!IsNavigationVisualActive()) - { - RefreshGamepadFocus(false); - } - } -} - -void UGarageWidget::OnSelectableItemClicked(USelectableItem* ClickedItem) -{ - RefreshAllItemsOwnership(); - if (ClickedItem && !ClickedItem->IsItemSelectable()) - { - HoveredItem.Reset(); - RefreshGamepadFocus(false); - } - else - { - OnSelectableItemInteracted(ClickedItem); - } -} - -void UGarageWidget::RefreshOwnershipAndFocus(bool bScrollIntoView) -{ - RefreshAllItemsOwnership(); - RefreshGamepadFocus(bScrollIntoView); -} - -void UGarageWidget::CancelPendingPress() -{ - if (USelectableItem* PressedItem = GamepadPressedItem.Get()) - { - PressedItem->SetButtonPressed(false); - } - GamepadPressedItem.Reset(); - if (bBackButtonPressed) - { - bBackButtonPressed = false; - RefreshGamepadFocus(false); - } -} - -void UGarageWidget::RefreshGamepadFocus(bool bScrollIntoView) -{ - const ATrivialKartPlayerController* PC = Cast(GetOwningPlayer()); - const bool bShowNavVisual = IsNavigationVisualActive(); - const bool bAllowMouseHoverVisual = (!bShowNavVisual && PC && PC->GetActiveInputMode() == ETrivialKartInputMode::KeyboardMouse); - - TArray ActiveItems; - if (ContentSwitcher) - { - GatherSelectableItems(ContentSwitcher->GetActiveWidget(), ActiveItems, true); - } - - USelectableItem* FocusedItem = nullptr; - if (ActiveItems.Num() == 0 && FocusedItemIndex >= 0) - { - FocusedItemIndex = -1; - } - else if (FocusedItemIndex >= 0) - { - FocusedItemIndex = FMath::Clamp(FocusedItemIndex, 0, ActiveItems.Num() - 1); - FocusedItem = ActiveItems[FocusedItemIndex]; - } - - TArray AllItems; - GatherSelectableItems(ContentSwitcher, AllItems, false); - for (USelectableItem* Item : AllItems) - { - if (Item) - { - const bool bIsInActiveTab = ActiveItems.Contains(Item); - Item->OnItemInteracted.BindUObject(this, &UGarageWidget::OnSelectableItemInteracted); - Item->OnItemUnhovered.BindUObject(this, &UGarageWidget::OnSelectableItemUnhovered); - Item->OnItemClicked.BindUObject(this, &UGarageWidget::OnSelectableItemClicked); - if (!bIsInActiveTab || (Item != GamepadPressedItem.Get() && !Item->IsButtonHovered())) - { - Item->SetButtonPressed(false); - } - const bool bIsHoveredByMouse = (bAllowMouseHoverVisual && bIsInActiveTab && HoveredItem.Get() == Item && Item->IsButtonHovered()); - const bool bIsFocusedTarget = bShowNavVisual ? (Item == FocusedItem) : bIsHoveredByMouse; - Item->SetGamepadFocused(bIsFocusedTarget, bShowNavVisual || bIsHoveredByMouse); - } - } - - if (FocusedItem && bScrollIntoView && bShowNavVisual) - { - for (UPanelWidget* Parent = FocusedItem->GetParent(); Parent != nullptr; Parent = Parent->GetParent()) - { - if (UScrollBox* ScrollBox = Cast(Parent)) - { - ScrollBox->ScrollWidgetIntoView(FocusedItem, true, EDescendantScrollDestination::IntoView); - break; - } - } - } - - if (BackButton && bBackStyleCached) - { - const bool bBackFocused = bShowNavVisual && (FocusedItemIndex == -2); - BackButton->SetRenderTransformPivot(FVector2D(0.5f, 0.5f)); - if (bBackFocused) - { - const bool bPressed = bBackButtonPressed || BackButton->IsPressed(); - FSlateBrush HighlightBrush; - HighlightBrush.DrawAs = ESlateBrushDrawType::RoundedBox; - HighlightBrush.TintColor = FSlateColor(bPressed - ? FLinearColor(1.0f, 0.35f, 0.0f, 0.68f) - : FLinearColor(1.0f, 0.45f, 0.0f, 0.48f)); - HighlightBrush.OutlineSettings.CornerRadii = FVector4(10.0f, 10.0f, 10.0f, 10.0f); - HighlightBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; - HighlightBrush.OutlineSettings.Color = FSlateColor(FLinearColor(1.0f, 0.9f, 0.0f, 1.0f)); - HighlightBrush.OutlineSettings.Width = 6.0f; - - FButtonStyle FocusedStyle = OriginalBackButtonStyle; - FocusedStyle.SetNormal(HighlightBrush); - FocusedStyle.SetHovered(HighlightBrush); - FocusedStyle.SetPressed(HighlightBrush); - BackButton->SetStyle(FocusedStyle); - BackButton->SetBackgroundColor(FLinearColor::White); - BackButton->SetRenderScale(FVector2D(bPressed ? 0.88f : 1.12f, bPressed ? 0.88f : 1.12f)); - } - else - { - BackButton->SetStyle(OriginalBackButtonStyle); - BackButton->SetBackgroundColor(OriginalBackButtonBgColor); - BackButton->SetRenderScale(FVector2D(1.0f, 1.0f)); - } - } - - const bool bTabBarFocused = bShowNavVisual && (FocusedItemIndex == -1); - for (int32 i = 0; i < CheckBoxes.Num(); ++i) - { - UCheckBox* CB = CheckBoxes[i]; - UBorder* HighlightBorder = TabHighlightBorders.IsValidIndex(i) ? TabHighlightBorders[i].Get() : nullptr; - if (!CB) - { - continue; - } - UWidget* TabScaleTarget = CB->GetParent() - ? static_cast(CB->GetParent()) - : static_cast(CB); - TabScaleTarget->SetRenderTransformPivot(FVector2D(0.5f, 0.5f)); - if (i == ActiveTabIndex) - { - if (HighlightBorder) - { - FSlateBrush OverlayBrush; - OverlayBrush.DrawAs = ESlateBrushDrawType::RoundedBox; - OverlayBrush.ImageSize = CB->GetWidgetStyle().CheckedImage.ImageSize; - OverlayBrush.TintColor = FSlateColor(FLinearColor(1.0f, 0.45f, 0.0f, 0.48f)); - OverlayBrush.OutlineSettings.CornerRadii = FVector4(8.0f, 8.0f, 8.0f, 8.0f); - OverlayBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; - OverlayBrush.OutlineSettings.Color = FSlateColor(bTabBarFocused - ? FLinearColor(1.0f, 0.9f, 0.0f, 1.0f) - : FLinearColor::Transparent); - OverlayBrush.OutlineSettings.Width = bTabBarFocused ? 6.0f : 0.0f; - HighlightBorder->SetBrush(OverlayBrush); - HighlightBorder->SetBrushColor(FLinearColor::White); - HighlightBorder->SetVisibility(ESlateVisibility::HitTestInvisible); - } - const float TargetTabScale = bTabBarFocused ? 1.15f : 1.0f; - TabScaleTarget->SetRenderScale(FVector2D(TargetTabScale, TargetTabScale)); - } - else - { - if (HighlightBorder) - { - HighlightBorder->SetVisibility(ESlateVisibility::Collapsed); - } - TabScaleTarget->SetRenderScale(FVector2D(1.0f, 1.0f)); - } - } -} - -bool UGarageWidget::HandleGamepadKey(const FKey& Key, bool bIsPressed) -{ - if (!bIsPressed) - { - if (Key == EKeys::Gamepad_FaceButton_Bottom) - { - if (bBackButtonPressed) - { - bBackButtonPressed = false; - RefreshGamepadFocus(false); - if (FocusedItemIndex == -2) - { - OnBackButtonClicked(); - } - return true; - } - - USelectableItem* PreviouslyPressed = GamepadPressedItem.Get(); - GamepadPressedItem.Reset(); - - TArray ActiveItems; - if (ContentSwitcher) - { - GatherSelectableItems(ContentSwitcher->GetActiveWidget(), ActiveItems, true); - } - if (PreviouslyPressed && FocusedItemIndex >= 0 && FocusedItemIndex < ActiveItems.Num() && - ActiveItems[FocusedItemIndex] == PreviouslyPressed) - { - PreviouslyPressed->SetButtonPressed(false); - PreviouslyPressed->OnSelectionButtonClicked(); - } - else if (PreviouslyPressed) - { - PreviouslyPressed->SetButtonPressed(false); - } - return true; - } - return false; - } - - if (Key == EKeys::Gamepad_FaceButton_Right) - { - CancelPendingPress(); - OnBackButtonClicked(); - return true; - } - if (Key == EKeys::Gamepad_LeftShoulder) - { - SelectTabByIndex(ActiveTabIndex - 1); - return true; - } - if (Key == EKeys::Gamepad_RightShoulder) - { - SelectTabByIndex(ActiveTabIndex + 1); - return true; - } - - TArray ActiveItems; - if (ContentSwitcher) - { - GatherSelectableItems(ContentSwitcher->GetActiveWidget(), ActiveItems, true); - } - - // If opened via touch/mouse with navigation focus hidden, reveal focus on the first navigation/confirm press - if (!IsNavigationVisualActive()) - { - if (Key == EKeys::Gamepad_DPad_Left || Key == EKeys::Gamepad_DPad_Right || - Key == EKeys::Gamepad_DPad_Up || Key == EKeys::Gamepad_DPad_Down || - Key == EKeys::Gamepad_FaceButton_Bottom) - { - CancelPendingPress(); - if (Key == EKeys::Gamepad_DPad_Up || ActiveItems.Num() == 0) - { - FocusedItemIndex = -1; - } - else if (FocusedItemIndex < 0) - { - FocusedItemIndex = (ActiveTabIndex == 0) ? FindActiveCarItemIndex() : 0; - } - if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) - { - PC->SetKeyNavigationActive(true); - } - RefreshGamepadFocus(true); - return true; - } - } - - if (Key == EKeys::Gamepad_DPad_Left) - { - CancelPendingPress(); - if (FocusedItemIndex == -2) - { - RefreshGamepadFocus(false); - } - else if (FocusedItemIndex == -1) - { - SelectTabByIndex(ActiveTabIndex - 1); - } - else if (ActiveItems.Num() > 1) - { - FocusedItemIndex = (FocusedItemIndex + ActiveItems.Num() - 1) % ActiveItems.Num(); - RefreshGamepadFocus(); - } - else - { - RefreshGamepadFocus(); - } - return true; - } - if (Key == EKeys::Gamepad_DPad_Right) - { - CancelPendingPress(); - if (FocusedItemIndex == -2) - { - RefreshGamepadFocus(false); - } - else if (FocusedItemIndex == -1) - { - SelectTabByIndex(ActiveTabIndex + 1); - } - else if (ActiveItems.Num() > 1) - { - FocusedItemIndex = (FocusedItemIndex + 1) % ActiveItems.Num(); - RefreshGamepadFocus(); - } - else - { - RefreshGamepadFocus(); - } - return true; - } - if (Key == EKeys::Gamepad_DPad_Up) - { - CancelPendingPress(); - if (FocusedItemIndex >= 0) - { - FocusedItemIndex = -1; - } - else if (FocusedItemIndex == -1 && BackButton) - { - FocusedItemIndex = -2; - } - RefreshGamepadFocus(false); - return true; - } - if (Key == EKeys::Gamepad_DPad_Down) - { - CancelPendingPress(); - if (FocusedItemIndex == -2) - { - FocusedItemIndex = -1; - } - else if (FocusedItemIndex == -1 && ActiveItems.Num() > 0) - { - FocusedItemIndex = (ActiveTabIndex == 0) ? FindActiveCarItemIndex() : 0; - } - RefreshGamepadFocus(); - return true; - } - if (Key == EKeys::Gamepad_FaceButton_Bottom) - { - if (FocusedItemIndex == -2 && BackButton) - { - bBackButtonPressed = true; - RefreshGamepadFocus(false); - } - else if (FocusedItemIndex >= 0 && FocusedItemIndex < ActiveItems.Num()) - { - GamepadPressedItem = ActiveItems[FocusedItemIndex]; - GamepadPressedItem->SetButtonPressed(true); - } - else if (FocusedItemIndex == -1 && ActiveItems.Num() > 0) - { - GamepadPressedItem.Reset(); - FocusedItemIndex = (ActiveTabIndex == 0) ? FindActiveCarItemIndex() : 0; - RefreshGamepadFocus(); - } - return true; - } - - return false; -} - void UGarageWidget::OnKartBoxStateChanged(bool bIsChecked) { SetCheckBoxState(bIsChecked, KartCheckBox, 0); diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/PGSWidget.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/PGSWidget.cpp index a6713611..26fbd4b9 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/PGSWidget.cpp +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/PGSWidget.cpp @@ -16,149 +16,87 @@ #include "Widgets/PGSWidget.h" -#include "OnlineSubsystem.h" -#include "OnlineSubsystemUtils.h" -#include "Actors/TrivialKartHUD.h" -#include "Blueprint/WidgetTree.h" -#include "Components/Border.h" -#include "Components/Button.h" #include "Components/CheckBox.h" -#include "Components/HorizontalBox.h" -#include "Components/Image.h" -#include "Components/Overlay.h" -#include "Components/OverlaySlot.h" #include "Components/ScrollBox.h" -#include "Components/TextBlock.h" #include "Components/VerticalBox.h" -#include "Components/WidgetSwitcher.h" #include "GameInstances/TrivialKartGameInstance.h" #include "Interfaces/OnlineAchievementsInterface.h" +#include "OnlineSubsystem.h" +#include "OnlineSubsystemUtils.h" #include "Widgets/PGSLayoutText.h" -static UBorder* EnsurePGSTabHighlightBorder(UWidgetTree* WidgetTree, UCheckBox* CB) +void UPGSWidget::RegisterTabCheckBoxes(TArray& OutCheckBoxes) { - UOverlay* ParentOverlay = CB ? Cast(CB->GetParent()) : nullptr; - if (!WidgetTree || !ParentOverlay) - { - return nullptr; - } - - UBorder* Border = WidgetTree->ConstructWidget(UBorder::StaticClass()); - Border->SetVisibility(ESlateVisibility::Collapsed); - Border->SetPadding(FMargin(0.0f)); - if (UOverlaySlot* OverlaySlot = ParentOverlay->AddChildToOverlay(Border)) - { - OverlaySlot->SetHorizontalAlignment(HAlign_Fill); - OverlaySlot->SetVerticalAlignment(VAlign_Fill); - } - return Border; + OutCheckBoxes.Add(AuthenticationCheckBox); + OutCheckBoxes.Add(AchievementsCheckBox); + OutCheckBoxes.Add(LeaderboardCheckBox); } -void UPGSWidget::NativeConstruct() +void UPGSWidget::BindTabCheckBoxEvents() { - Super::NativeConstruct(); - - // Keep the modal root hit-testable so empty modal space blocks clicks from piercing into FSceneViewport - SetVisibility(ESlateVisibility::Visible); - - if (WidgetTree) + if (AuthenticationCheckBox) { - UWidget* TreeRoot = WidgetTree->RootWidget; - WidgetTree->ForEachWidget([TreeRoot](UWidget* Widget) - { - if (!Widget || Widget == TreeRoot || Widget->GetVisibility() != ESlateVisibility::Visible) - { - return; - } - if (Cast(Widget) || Cast(Widget)) - { - Widget->SetVisibility(ESlateVisibility::HitTestInvisible); - } - else if (Cast(Widget) || Cast(Widget) || Cast(Widget)) - { - Widget->SetVisibility(ESlateVisibility::SelfHitTestInvisible); - } - }); + AuthenticationCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UPGSWidget::OnAuthCheckBoxStateChanged); } - - if (BackButton) + if (AchievementsCheckBox) { - if (!bBackStyleCached) - { - OriginalBackButtonStyle = BackButton->GetStyle(); - OriginalBackButtonBgColor = BackButton->GetBackgroundColor(); - bBackStyleCached = true; - } - BackButton->OnClicked.AddUniqueDynamic(this, &UPGSWidget::OnBackButtonClicked); - BackButton->OnReleased.AddUniqueDynamic(this, &UPGSWidget::OnBackButtonReleased); + AchievementsCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UPGSWidget::OnAchievementBoxStateChange); } - - CheckBoxes.Empty(); - CheckBoxes.Add(AuthenticationCheckBox); - CheckBoxes.Add(AchievementsCheckBox); - CheckBoxes.Add(LeaderboardCheckBox); - - if (TabHighlightBorders.Num() != CheckBoxes.Num()) + if (LeaderboardCheckBox) { - TabHighlightBorders.Empty(); - for (UCheckBox* CB : CheckBoxes) - { - TabHighlightBorders.Add(EnsurePGSTabHighlightBorder(WidgetTree, CB)); - } + LeaderboardCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UPGSWidget::OnLeaderboardBoxStateChange); } +} +void UPGSWidget::UnbindTabCheckBoxEvents() +{ if (AuthenticationCheckBox) { - AuthenticationCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UPGSWidget::OnAuthCheckBoxStateChanged); + AuthenticationCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UPGSWidget::OnAuthCheckBoxStateChanged); } if (AchievementsCheckBox) { - AchievementsCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UPGSWidget::OnAchievementBoxStateChange); + AchievementsCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UPGSWidget::OnAchievementBoxStateChange); } if (LeaderboardCheckBox) { - LeaderboardCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UPGSWidget::OnLeaderboardBoxStateChange); - } - - if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) - { - PC->OnInputModeUpdated.RemoveAll(this); - PC->OnInputModeUpdated.AddUObject(this, &UPGSWidget::OnInputModeChanged); + LeaderboardCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UPGSWidget::OnLeaderboardBoxStateChange); } +} - if (TWeakObjectPtr Instance = Cast(GetGameInstance()); +void UPGSWidget::InitializeModalContent() +{ + if (TWeakObjectPtr Instance = Cast(GetGameInstance()); Instance.IsValid() && AuthBox && PGSTextTemplate) { const FString AuthStatus = Instance->GetLoginStatus() ? FString("Logged In") : FString("Logged Out"); - if (const auto PgsAuthStatusText = Cast( - CreateWidget(this, PGSTextTemplate))) + if (UPGSLayoutText* PgsAuthStatusText = Cast(CreateWidget(this, PGSTextTemplate))) { PgsAuthStatusText->SetPGSText("Auth Status", AuthStatus); AuthBox->AddChildToVerticalBox(PgsAuthStatusText); } - if (const auto PgsUsernameText = Cast( - CreateWidget(this, PGSTextTemplate))) + if (UPGSLayoutText* PgsUsernameText = Cast(CreateWidget(this, PGSTextTemplate))) { PgsUsernameText->SetPGSText("Username", Instance->GetPlayerName()); AuthBox->AddChildToVerticalBox(PgsUsernameText); } } - if (const IOnlineIdentityPtr IdentityInterface = Online::GetIdentityInterface(GetWorld()); + + if (const IOnlineIdentityPtr IdentityInterface = Online::GetIdentityInterface(GetWorld()); IdentityInterface.IsValid() && AchievementsBox && PGSTextTemplate) { if (const TSharedPtr UniquePlayerId = IdentityInterface->GetUniquePlayerId(0); UniquePlayerId.IsValid()) { - if (const IOnlineAchievementsPtr AchievementsInterface = + if (const IOnlineAchievementsPtr AchievementsInterface = Online::GetAchievementsInterface(GetWorld()); AchievementsInterface.IsValid()) { TArray Achievements; - if (AchievementsInterface->GetCachedAchievements(*UniquePlayerId, Achievements) + if (AchievementsInterface->GetCachedAchievements(*UniquePlayerId, Achievements) == EOnlineCachedResult::Success) { - for (auto Achievement : Achievements) + for (const FOnlineAchievement& Achievement : Achievements) { - if (auto PGSText = Cast( - CreateWidget(this, PGSTextTemplate))) + if (UPGSLayoutText* PGSText = Cast(CreateWidget(this, PGSTextTemplate))) { PGSText->SetPGSText(Achievement.Id, FString::Printf(TEXT("%.1f"), Achievement.Progress)); AchievementsBox->AddChild(PGSText); @@ -168,317 +106,19 @@ void UPGSWidget::NativeConstruct() } } } - - bBackButtonFocused = false; - bBackButtonPressed = false; - ActiveTabIndex = ContentSwitcher ? ContentSwitcher->GetActiveWidgetIndex() : 0; - UpdateTabFocusVisuals(); -} - -void UPGSWidget::NativeDestruct() -{ - if (BackButton) - { - BackButton->OnClicked.RemoveDynamic(this, &UPGSWidget::OnBackButtonClicked); - BackButton->OnReleased.RemoveDynamic(this, &UPGSWidget::OnBackButtonReleased); - } - if (AuthenticationCheckBox) - { - AuthenticationCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UPGSWidget::OnAuthCheckBoxStateChanged); - } - if (AchievementsCheckBox) - { - AchievementsCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UPGSWidget::OnAchievementBoxStateChange); - } - if (LeaderboardCheckBox) - { - LeaderboardCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UPGSWidget::OnLeaderboardBoxStateChange); - } - - if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) - { - PC->OnInputModeUpdated.RemoveAll(this); - } - - CheckBoxes.Empty(); - Super::NativeDestruct(); -} - -bool UPGSWidget::IsNavigationVisualActive() const -{ - if (const ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) - { - return PC->IsKeyNavigationActive(); - } - return false; -} - -void UPGSWidget::RestoreViewportFocus() const -{ - if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) - { - PC->RestoreFocusToGameViewport(); - } -} - -void UPGSWidget::OnInputModeChanged(ETrivialKartInputMode NewInputMode) -{ - if (!IsNavigationVisualActive()) - { - CancelPendingPress(); - } - UpdateTabFocusVisuals(); -} - -void UPGSWidget::CancelPendingPress() -{ - if (bBackButtonPressed) - { - bBackButtonPressed = false; - UpdateTabFocusVisuals(); - } -} - -void UPGSWidget::OnBackButtonReleased() -{ - RestoreViewportFocus(); -} - -void UPGSWidget::OnBackButtonClicked() -{ - if (TWeakObjectPtr PlayerController = GetOwningPlayer(); PlayerController.IsValid()) - { - if (const TWeakObjectPtr CurrentHUD = Cast(PlayerController->GetHUD()); - CurrentHUD.IsValid()) - { - CurrentHUD->AddWidgetToScreen(EWidgetType::PlayBoard); - CurrentHUD->RemoveWidgetFromScreen(EWidgetType::PGS); - } - } -} - -void UPGSWidget::SetCheckBoxState(bool bIsChecked, UCheckBox* CheckBox, int ActiveWidgetIndex) -{ - if (CheckBox == nullptr) - { - return; - } - CancelPendingPress(); - bBackButtonFocused = false; - if (bIsChecked) - { - ActiveTabIndex = ActiveWidgetIndex; - if (ContentSwitcher) - { - ContentSwitcher->SetActiveWidgetIndex(ActiveWidgetIndex); - } - for (auto CurrentCheckBox : CheckBoxes) - { - if (CurrentCheckBox && CurrentCheckBox != CheckBox) - { - CurrentCheckBox->SetCheckedState(ECheckBoxState::Unchecked); - } - } - } - else - { - CheckBox->SetCheckedState(ECheckBoxState::Checked); - } - UpdateTabFocusVisuals(); - RestoreViewportFocus(); -} - -void UPGSWidget::SelectTabByIndex(int32 NewTabIndex) -{ - if (CheckBoxes.Num() == 0) - { - return; - } - bBackButtonFocused = false; - ActiveTabIndex = (NewTabIndex + CheckBoxes.Num()) % CheckBoxes.Num(); - if (UCheckBox* TargetCheckBox = CheckBoxes[ActiveTabIndex]) - { - TargetCheckBox->SetCheckedState(ECheckBoxState::Checked); - SetCheckBoxState(true, TargetCheckBox, ActiveTabIndex); - } -} - -void UPGSWidget::UpdateTabFocusVisuals() -{ - const bool bShowNavVisual = IsNavigationVisualActive(); - - if (BackButton && bBackStyleCached) - { - const bool bBackActive = bShowNavVisual && bBackButtonFocused; - BackButton->SetRenderTransformPivot(FVector2D(0.5f, 0.5f)); - if (bBackActive) - { - const bool bPressed = bBackButtonPressed || BackButton->IsPressed(); - FSlateBrush HighlightBrush; - HighlightBrush.DrawAs = ESlateBrushDrawType::RoundedBox; - HighlightBrush.TintColor = FSlateColor(bPressed - ? FLinearColor(1.0f, 0.35f, 0.0f, 0.68f) - : FLinearColor(1.0f, 0.45f, 0.0f, 0.48f)); - HighlightBrush.OutlineSettings.CornerRadii = FVector4(10.0f, 10.0f, 10.0f, 10.0f); - HighlightBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; - HighlightBrush.OutlineSettings.Color = FSlateColor(FLinearColor(1.0f, 0.9f, 0.0f, 1.0f)); - HighlightBrush.OutlineSettings.Width = 6.0f; - - FButtonStyle FocusedStyle = OriginalBackButtonStyle; - FocusedStyle.SetNormal(HighlightBrush); - FocusedStyle.SetHovered(HighlightBrush); - FocusedStyle.SetPressed(HighlightBrush); - BackButton->SetStyle(FocusedStyle); - BackButton->SetBackgroundColor(FLinearColor::White); - BackButton->SetRenderScale(FVector2D(bPressed ? 0.88f : 1.12f, bPressed ? 0.88f : 1.12f)); - } - else - { - BackButton->SetStyle(OriginalBackButtonStyle); - BackButton->SetBackgroundColor(OriginalBackButtonBgColor); - BackButton->SetRenderScale(FVector2D(1.0f, 1.0f)); - } - } - - const bool bTabBarFocused = bShowNavVisual && !bBackButtonFocused; - for (int32 i = 0; i < CheckBoxes.Num(); ++i) - { - UCheckBox* CB = CheckBoxes[i]; - UBorder* HighlightBorder = TabHighlightBorders.IsValidIndex(i) ? TabHighlightBorders[i].Get() : nullptr; - if (!CB) - { - continue; - } - UWidget* TabScaleTarget = CB->GetParent() - ? static_cast(CB->GetParent()) - : static_cast(CB); - TabScaleTarget->SetRenderTransformPivot(FVector2D(0.5f, 0.5f)); - if (i == ActiveTabIndex) - { - if (HighlightBorder) - { - FSlateBrush OverlayBrush; - OverlayBrush.DrawAs = ESlateBrushDrawType::RoundedBox; - OverlayBrush.ImageSize = CB->GetWidgetStyle().CheckedImage.ImageSize; - OverlayBrush.TintColor = FSlateColor(FLinearColor(1.0f, 0.45f, 0.0f, 0.48f)); - OverlayBrush.OutlineSettings.CornerRadii = FVector4(8.0f, 8.0f, 8.0f, 8.0f); - OverlayBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; - OverlayBrush.OutlineSettings.Color = FSlateColor(bTabBarFocused - ? FLinearColor(1.0f, 0.9f, 0.0f, 1.0f) - : FLinearColor::Transparent); - OverlayBrush.OutlineSettings.Width = bTabBarFocused ? 6.0f : 0.0f; - HighlightBorder->SetBrush(OverlayBrush); - HighlightBorder->SetBrushColor(FLinearColor::White); - HighlightBorder->SetVisibility(ESlateVisibility::HitTestInvisible); - } - const float TargetTabScale = bTabBarFocused ? 1.15f : 1.0f; - TabScaleTarget->SetRenderScale(FVector2D(TargetTabScale, TargetTabScale)); - } - else - { - if (HighlightBorder) - { - HighlightBorder->SetVisibility(ESlateVisibility::Collapsed); - } - TabScaleTarget->SetRenderScale(FVector2D(1.0f, 1.0f)); - } - } } -bool UPGSWidget::HandleGamepadKey(const FKey& Key, bool bIsPressed) +UScrollBox* UPGSWidget::GetActiveReadOnlyScrollBox() const { - if (!bIsPressed) - { - if (Key == EKeys::Gamepad_FaceButton_Bottom && bBackButtonPressed) - { - bBackButtonPressed = false; - UpdateTabFocusVisuals(); - if (bBackButtonFocused) - { - OnBackButtonClicked(); - } - return true; - } - return false; - } - - if (Key == EKeys::Gamepad_FaceButton_Right) - { - CancelPendingPress(); - OnBackButtonClicked(); - return true; - } - if (!IsNavigationVisualActive() && - (Key == EKeys::Gamepad_DPad_Left || Key == EKeys::Gamepad_DPad_Right || - Key == EKeys::Gamepad_DPad_Up || Key == EKeys::Gamepad_DPad_Down || - Key == EKeys::Gamepad_FaceButton_Bottom)) - { - if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) - { - PC->SetKeyNavigationActive(true); - } - UpdateTabFocusVisuals(); - return true; - } - if (Key == EKeys::Gamepad_FaceButton_Bottom) - { - if (bBackButtonFocused && BackButton) - { - bBackButtonPressed = true; - UpdateTabFocusVisuals(); - } - return true; - } - if (Key == EKeys::Gamepad_LeftShoulder || Key == EKeys::Gamepad_DPad_Left) - { - if (bBackButtonFocused && Key == EKeys::Gamepad_DPad_Left) - { - return true; - } - SelectTabByIndex(ActiveTabIndex - 1); - return true; - } - if (Key == EKeys::Gamepad_RightShoulder || Key == EKeys::Gamepad_DPad_Right) - { - if (bBackButtonFocused && Key == EKeys::Gamepad_DPad_Right) - { - return true; - } - SelectTabByIndex(ActiveTabIndex + 1); - return true; - } - if (Key == EKeys::Gamepad_DPad_Up) + if (ActiveTabIndex == 1) { - UScrollBox* TargetScroll = (ActiveTabIndex == 1) ? AchievementsBox.Get() : ((ActiveTabIndex == 2) ? LeaderboardBox.Get() : nullptr); - if (!bBackButtonFocused && TargetScroll && TargetScroll->GetScrollOffset() > KINDA_SMALL_NUMBER) - { - const float MaxOffset = FMath::Max(0.0f, TargetScroll->GetScrollOffsetOfEnd()); - TargetScroll->SetScrollOffset(FMath::Clamp(TargetScroll->GetScrollOffset() - 60.0f, 0.0f, MaxOffset)); - } - else if (!bBackButtonFocused && BackButton) - { - bBackButtonFocused = true; - UpdateTabFocusVisuals(); - } - return true; + return AchievementsBox.Get(); } - if (Key == EKeys::Gamepad_DPad_Down) + if (ActiveTabIndex == 2) { - if (bBackButtonFocused) - { - bBackButtonFocused = false; - UpdateTabFocusVisuals(); - return true; - } - UScrollBox* TargetScroll = (ActiveTabIndex == 1) ? AchievementsBox.Get() : ((ActiveTabIndex == 2) ? LeaderboardBox.Get() : nullptr); - if (TargetScroll) - { - const float MaxOffset = FMath::Max(0.0f, TargetScroll->GetScrollOffsetOfEnd()); - TargetScroll->SetScrollOffset(FMath::Clamp(TargetScroll->GetScrollOffset() + 60.0f, 0.0f, MaxOffset)); - } - return true; + return LeaderboardBox.Get(); } - return false; + return nullptr; } void UPGSWidget::OnAuthCheckBoxStateChanged(bool bIsChecked) diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/PlayBoardWidget.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/PlayBoardWidget.cpp index 22a18e14..216de258 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/PlayBoardWidget.cpp +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/PlayBoardWidget.cpp @@ -20,8 +20,9 @@ #include "Actors/TrivialKartHUD.h" #include "Blueprint/WidgetTree.h" #include "Components/Border.h" +#include "Components/BorderSlot.h" #include "Components/Button.h" -#include "Components/HorizontalBox.h" +#include "Components/ButtonSlot.h" #include "Components/Image.h" #include "Components/Overlay.h" #include "Components/OverlaySlot.h" @@ -32,16 +33,117 @@ #include "Components/VerticalBoxSlot.h" #include "Engine/Texture2D.h" #include "Infos/TrivialKartPlayerState.h" +#include "Styling/SlateTypes.h" +#include "Widgets/TrivialKartUIStyle.h" TSharedRef UPlayBoardWidget::RebuildWidget() { if (!IsDesignTime()) { EnsureInputGuideWidget(); + EnsureMenuButtonHighlightFrames(); } return Super::RebuildWidget(); } +void UPlayBoardWidget::EnsureMenuButtonHighlightFrames() +{ + if (IsDesignTime() || !WidgetTree) + { + return; + } + + UButton* Buttons[3] = { GarageButton.Get(), PGSButton.Get(), StoreButton.Get() }; + for (int32 i = 0; i < 3; ++i) + { + UButton* Btn = Buttons[i]; + if (!Btn) + { + continue; + } + if (MenuButtonHighlightBorders[i].IsValid() && Btn->GetContent() == MenuButtonHighlightBorders[i].Get()) + { + continue; + } + + UWidget* ExistingContent = Btn->GetContent(); + if (!ExistingContent) + { + continue; + } + + FMargin OrigPad(0.0f, 50.0f, 0.0f, 50.0f); + if (const UButtonSlot* OldBtnSlot = Cast(Btn->GetContentSlot())) + { + OrigPad = OldBtnSlot->GetPadding(); + } + + UBorder* HighlightFrame = WidgetTree->ConstructWidget(UBorder::StaticClass()); + if (!HighlightFrame) + { + continue; + } + + // Use symmetric outer/inner vertical insets and generous horizontal insets so every button's + // label/icon stays dead-center inside its highlight box while clearing rounded phone screen corners. + constexpr float OuterHorizontal = 34.0f; + constexpr float OuterVertical = 18.0f; + constexpr float InnerHorizontal = 12.0f; + + const float OrigVerticalAvg = 0.5f * (OrigPad.Top + OrigPad.Bottom); + float InnerVertical = FMath::Max(10.0f, OrigVerticalAvg - OuterVertical); + if (UImage* IconImage = Cast(ExistingContent)) + { + const FVector2D OrigSize = IconImage->GetBrush().ImageSize; + if (OrigSize.Y > 88.0f) + { + const float Aspect = (OrigSize.Y > KINDA_SMALL_NUMBER) ? (OrigSize.X / OrigSize.Y) : 1.0f; + IconImage->SetDesiredSizeOverride(FVector2D(88.0f * Aspect, 88.0f)); + } + InnerVertical = 10.0f; + } + else if (UTextBlock* LabelText = Cast(ExistingContent)) + { + LabelText->SetJustification(ETextJustify::Center); + } + + const FMargin InnerPadding(InnerHorizontal, InnerVertical, InnerHorizontal, InnerVertical); + + ExistingContent->RemoveFromParent(); + + HighlightFrame->SetBrush(TrivialKartUIStyle::GetEmptyBrush()); + HighlightFrame->SetBrushColor(FLinearColor::Transparent); + HighlightFrame->SetVisibility(ESlateVisibility::SelfHitTestInvisible); + HighlightFrame->SetRenderTransformPivot(FVector2D(0.5f, 0.5f)); + HighlightFrame->SetHorizontalAlignment(HAlign_Center); + HighlightFrame->SetVerticalAlignment(VAlign_Center); + HighlightFrame->SetPadding(InnerPadding); + + if (UBorderSlot* BorderSlot = Cast(HighlightFrame->SetContent(ExistingContent))) + { + BorderSlot->SetHorizontalAlignment(HAlign_Center); + BorderSlot->SetVerticalAlignment(VAlign_Center); + BorderSlot->SetPadding(InnerPadding); + } + + if (UButtonSlot* NewBtnSlot = Cast(Btn->SetContent(HighlightFrame))) + { + NewBtnSlot->SetHorizontalAlignment(HAlign_Fill); + NewBtnSlot->SetVerticalAlignment(VAlign_Fill); + NewBtnSlot->SetPadding(FMargin(OuterHorizontal, OuterVertical, OuterHorizontal, OuterVertical)); + } + + FButtonStyle SteadyBarStyle = Btn->GetStyle(); + SteadyBarStyle.SetHovered(SteadyBarStyle.Normal); + SteadyBarStyle.SetPressed(SteadyBarStyle.Normal); + SteadyBarStyle.SetNormalPadding(FMargin(12.0f, 0.0f, 12.0f, 0.0f)); + SteadyBarStyle.SetPressedPadding(FMargin(12.0f, 0.0f, 12.0f, 0.0f)); + Btn->SetStyle(SteadyBarStyle); + + MenuButtonHighlightBorders[i] = HighlightFrame; + } +} + void UPlayBoardWidget::EnsureInputGuideWidget() { if (IsDesignTime() || InputGuideText.IsValid() || !WidgetTree || !WidgetTree->RootWidget) @@ -78,19 +180,15 @@ void UPlayBoardWidget::EnsureInputGuideWidget() return; } - InputGuideBorder = GuideBorder; InputGuideText = GuideText; GuideBorder->SetVisibility(ESlateVisibility::HitTestInvisible); GuideBorder->SetPadding(FMargin(24.0f, 10.0f, 24.0f, 10.0f)); - FSlateBrush BannerBrush; - BannerBrush.DrawAs = ESlateBrushDrawType::RoundedBox; - BannerBrush.TintColor = FSlateColor(FLinearColor(0.05f, 0.08f, 0.14f, 0.78f)); - BannerBrush.OutlineSettings.CornerRadii = FVector4(12.0f, 12.0f, 12.0f, 12.0f); - BannerBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; - BannerBrush.OutlineSettings.Color = FSlateColor(FLinearColor(1.0f, 0.85f, 0.2f, 0.9f)); - BannerBrush.OutlineSettings.Width = 2.5f; - GuideBorder->SetBrush(BannerBrush); + GuideBorder->SetBrush(TrivialKartUIStyle::MakeRoundedHighlightBrush( + 12.0f, + 2.5f, + FLinearColor(0.05f, 0.08f, 0.14f, 0.78f), + FLinearColor(1.0f, 0.85f, 0.2f, 0.9f))); GuideBorder->SetBrushColor(FLinearColor::White); GuideText->SetVisibility(ESlateVisibility::HitTestInvisible); @@ -131,14 +229,11 @@ void UPlayBoardWidget::EnsureInputGuideWidget() PadBorder->SetVerticalAlignment(VAlign_Center); PadBorder->SetPadding(FMargin(18.0f)); - FSlateBrush PadBrush; - PadBrush.DrawAs = ESlateBrushDrawType::RoundedBox; - PadBrush.TintColor = FSlateColor(FLinearColor(0.04f, 0.07f, 0.14f, 0.72f)); - PadBrush.OutlineSettings.CornerRadii = FVector4(123.0f, 123.0f, 123.0f, 123.0f); - PadBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; - PadBrush.OutlineSettings.Color = FSlateColor(FLinearColor(1.0f, 0.85f, 0.2f, 0.9f)); - PadBrush.OutlineSettings.Width = 4.5f; - PadBorder->SetBrush(PadBrush); + PadBorder->SetBrush(TrivialKartUIStyle::MakeRoundedHighlightBrush( + 123.0f, + 4.5f, + FLinearColor(0.04f, 0.07f, 0.14f, 0.72f), + FLinearColor(1.0f, 0.85f, 0.2f, 0.9f))); PadBorder->SetBrushColor(FLinearColor::White); HandIconImage->SetVisibility(ESlateVisibility::HitTestInvisible); @@ -214,11 +309,17 @@ void UPlayBoardWidget::UpdateInputGuideText(ETrivialKartInputMode InputMode) return; } - if (LastRenderedGuideMode.IsSet() && LastRenderedGuideMode.GetValue() == InputMode) + const ATrivialKartPlayerController* PC = Cast(GetOwningPlayer()); + const ETrivialKartGamepadStyle GamepadStyle = PC ? PC->GetActiveGamepadStyle() : ETrivialKartGamepadStyle::GenericXbox; + + if (LastRenderedGuideMode.IsSet() && LastRenderedGuideMode.GetValue() == InputMode && + (InputMode != ETrivialKartInputMode::Gamepad || + (LastRenderedGamepadStyle.IsSet() && LastRenderedGamepadStyle.GetValue() == GamepadStyle))) { return; } LastRenderedGuideMode = InputMode; + LastRenderedGamepadStyle = GamepadStyle; const ESlateVisibility TouchPadVisibility = (InputMode == ETrivialKartInputMode::Touch) ? ESlateVisibility::HitTestInvisible @@ -238,7 +339,18 @@ void UPlayBoardWidget::UpdateInputGuideText(ETrivialKartInputMode InputMode) InputGuideText->SetText(NSLOCTEXT("TrivialKart", "GuideTouch", "Touch and hold to drive")); break; case ETrivialKartInputMode::Gamepad: - InputGuideText->SetText(NSLOCTEXT("TrivialKart", "GuideGamepad", "Hold Trigger, A, or D-Pad Right to drive")); + switch (GamepadStyle) + { + case ETrivialKartGamepadStyle::PlayStation: + InputGuideText->SetText(NSLOCTEXT("TrivialKart", "GuideGamepadPS", "Hold Trigger, X, or D-Pad Right to drive")); + break; + case ETrivialKartGamepadStyle::NintendoSwitch: + InputGuideText->SetText(NSLOCTEXT("TrivialKart", "GuideGamepadSwitch", "Hold Trigger, B, or D-Pad Right to drive")); + break; + default: + InputGuideText->SetText(NSLOCTEXT("TrivialKart", "GuideGamepad", "Hold Trigger, A, or D-Pad Right to drive")); + break; + } break; case ETrivialKartInputMode::KeyboardMouse: InputGuideText->SetText(NSLOCTEXT("TrivialKart", "GuideKeyboardMouse", "Hold Spacebar or Click to drive")); @@ -251,7 +363,9 @@ void UPlayBoardWidget::NativeConstruct() Super::NativeConstruct(); LastRenderedGuideMode.Reset(); + LastRenderedGamepadStyle.Reset(); EnsureInputGuideWidget(); + EnsureMenuButtonHighlightFrames(); // If RebuildWidget ran before HUD was ready, ensure the cached hand texture is assigned now if (TouchDrivePadBorder.IsValid()) @@ -277,24 +391,7 @@ void UPlayBoardWidget::NativeConstruct() } } - if (WidgetTree) - { - WidgetTree->ForEachWidget([](UWidget* Widget) - { - if (!Widget || Widget->GetVisibility() != ESlateVisibility::Visible) - { - return; - } - if (Cast(Widget) || Cast(Widget)) - { - Widget->SetVisibility(ESlateVisibility::HitTestInvisible); - } - else if (Cast(Widget) || Cast(Widget) || Cast(Widget)) - { - Widget->SetVisibility(ESlateVisibility::SelfHitTestInvisible); - } - }); - } + TrivialKartUIStyle::NormalizeWidgetTreeHitTesting(WidgetTree); if (ATrivialKartPlayerController* PlayerController = Cast(GetOwningPlayer())) { @@ -338,20 +435,6 @@ void UPlayBoardWidget::NativeConstruct() StoreButton->OnPressed.AddUniqueDynamic(this, &ThisClass::OnStoreButtonPressed); StoreButton->OnReleased.AddUniqueDynamic(this, &ThisClass::OnMenuButtonReleased); } - - if (!bStylesCached) - { - UButton* Buttons[3] = { GarageButton.Get(), PGSButton.Get(), StoreButton.Get() }; - for (int32 i = 0; i < 3; ++i) - { - if (Buttons[i]) - { - OriginalButtonStyles[i] = Buttons[i]->GetStyle(); - OriginalBackgroundColors[i] = Buttons[i]->GetBackgroundColor(); - } - } - bStylesCached = true; - } FocusedButtonIndex = -1; PressedButtonIndex = -1; @@ -679,15 +762,6 @@ bool UPlayBoardWidget::HandleGamepadKey(const FKey& Key, bool bIsPressed, bool b return false; } - if (Key == EKeys::Gamepad_RightTrigger || Key == EKeys::Gamepad_LeftTrigger) - { - if (FocusedButtonIndex >= 0) - { - ClearMenuFocus(false); - } - return false; - } - return false; } @@ -697,40 +771,26 @@ void UPlayBoardWidget::UpdateButtonFocusVisuals() for (int32 i = 0; i < 3; ++i) { - if (!Buttons[i]) + UButton* Btn = Buttons[i]; + UBorder* HighlightFrame = MenuButtonHighlightBorders[i].Get(); + if (!Btn || !HighlightFrame) { continue; } - Buttons[i]->SetRenderTransformPivot(FVector2D(0.5f, 0.5f)); + if (i == FocusedButtonIndex) { - const bool bIsPressed = (i == PressedButtonIndex) || Buttons[i]->IsPressed(); - FSlateBrush HighlightBrush; - HighlightBrush.DrawAs = ESlateBrushDrawType::RoundedBox; - HighlightBrush.TintColor = FSlateColor(bIsPressed - ? FLinearColor(1.0f, 0.35f, 0.0f, 0.68f) - : FLinearColor(1.0f, 0.45f, 0.0f, 0.48f)); - HighlightBrush.OutlineSettings.CornerRadii = FVector4(12.0f, 12.0f, 12.0f, 12.0f); - HighlightBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; - HighlightBrush.OutlineSettings.Color = FSlateColor(FLinearColor(1.0f, 0.9f, 0.0f, 1.0f)); - HighlightBrush.OutlineSettings.Width = 6.0f; - - FButtonStyle FocusedStyle = OriginalButtonStyles[i]; - FocusedStyle.SetNormal(HighlightBrush); - FocusedStyle.SetHovered(HighlightBrush); - FocusedStyle.SetPressed(HighlightBrush); - Buttons[i]->SetStyle(FocusedStyle); - Buttons[i]->SetBackgroundColor(FLinearColor::White); - Buttons[i]->SetColorAndOpacity(FLinearColor::White); - const float TargetScale = bIsPressed ? 0.88f : 1.12f; - Buttons[i]->SetRenderScale(FVector2D(TargetScale, TargetScale)); + const bool bIsPressed = (i == PressedButtonIndex) || Btn->IsPressed(); + HighlightFrame->SetBrush(TrivialKartUIStyle::MakeButtonFocusBrush(bIsPressed, 16.0f)); + HighlightFrame->SetBrushColor(FLinearColor::White); + const float TargetScale = bIsPressed ? 0.95f : 1.02f; + HighlightFrame->SetRenderScale(FVector2D(TargetScale, TargetScale)); } else { - Buttons[i]->SetStyle(OriginalButtonStyles[i]); - Buttons[i]->SetBackgroundColor(OriginalBackgroundColors[i]); - Buttons[i]->SetColorAndOpacity(FLinearColor::White); - Buttons[i]->SetRenderScale(FVector2D(1.0f, 1.0f)); + HighlightFrame->SetBrush(TrivialKartUIStyle::GetEmptyBrush()); + HighlightFrame->SetBrushColor(FLinearColor::Transparent); + HighlightFrame->SetRenderScale(FVector2D(1.0f, 1.0f)); } } diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/SelectableItem.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/SelectableItem.cpp index 74a88d05..acd9c370 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/SelectableItem.cpp +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/SelectableItem.cpp @@ -26,6 +26,7 @@ #include "GameInstances/TrivialKartGameInstance.h" #include "Infos/TrivialKartPlayerState.h" #include "Objects/TrivialKartSaveGame.h" +#include "Widgets/TrivialKartUIStyle.h" void USelectableItem::NativePreConstruct() { @@ -123,6 +124,7 @@ void USelectableItem::EnsureOverlayHitTestAndBorder() { OverlaySlot->SetHorizontalAlignment(HAlign_Fill); OverlaySlot->SetVerticalAlignment(VAlign_Fill); + OverlaySlot->SetPadding(FMargin(2.0f)); } } } @@ -171,6 +173,10 @@ void USelectableItem::OnSelectionButtonReleased() void USelectableItem::SetButtonPressed(bool bInPressed) { + if (bIsButtonPressed == bInPressed) + { + return; + } bIsButtonPressed = bInPressed; UpdateHighlightVisuals(); } @@ -214,11 +220,9 @@ void USelectableItem::OnSelectionButtonClicked() switch (PurchaseObject) { case EPurchaseObject::Car: - if (!CarType.IsEmpty()) + if (PlayerState->PurchaseCarWithCoins(CarType, CoinQuantity)) { - PlayerState->AddCarToInventory(CarType); SetIsEnabled(false); - PlayerState->ConsumeCoins(CoinQuantity); } break; case EPurchaseObject::Fuel: @@ -267,6 +271,10 @@ void USelectableItem::OnSelectionButtonClicked() void USelectableItem::SetGamepadFocused(bool bInFocused, bool bInShowVisual) { + if (bIsGamepadFocused == bInFocused && bShowFocusVisual == bInShowVisual) + { + return; + } bIsGamepadFocused = bInFocused; bShowFocusVisual = bInShowVisual; UpdateHighlightVisuals(); @@ -293,22 +301,16 @@ void USelectableItem::UpdateHighlightVisuals() { if (FocusHighlightBorder) { - FSlateBrush OverlayBrush; - OverlayBrush.DrawAs = ESlateBrushDrawType::RoundedBox; - OverlayBrush.TintColor = FSlateColor(bIsButtonPressed - ? FLinearColor(1.0f, 0.30f, 0.0f, 0.72f) - : FLinearColor(1.0f, 0.45f, 0.0f, 0.48f)); - OverlayBrush.OutlineSettings.CornerRadii = FVector4(12.0f, 12.0f, 12.0f, 12.0f); - OverlayBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; - OverlayBrush.OutlineSettings.Color = FSlateColor(bIsButtonPressed - ? FLinearColor(1.0f, 1.0f, 0.2f, 1.0f) - : FLinearColor(1.0f, 0.9f, 0.0f, 1.0f)); - OverlayBrush.OutlineSettings.Width = bIsButtonPressed ? 10.0f : 8.0f; + const FSlateBrush OverlayBrush = TrivialKartUIStyle::MakeRoundedHighlightBrush( + 12.0f, + bIsButtonPressed ? 10.0f : 8.0f, + bIsButtonPressed ? FLinearColor(1.0f, 0.30f, 0.0f, 0.72f) : FLinearColor(1.0f, 0.45f, 0.0f, 0.48f), + bIsButtonPressed ? FLinearColor(1.0f, 1.0f, 0.2f, 1.0f) : FLinearColor(1.0f, 0.9f, 0.0f, 1.0f)); FocusHighlightBorder->SetBrush(OverlayBrush); FocusHighlightBorder->SetBrushColor(FLinearColor::White); FocusHighlightBorder->SetVisibility(ESlateVisibility::HitTestInvisible); } - const float TargetScale = bIsButtonPressed ? 0.88f : 1.08f; + const float TargetScale = bIsButtonPressed ? 0.94f : 1.0f; ScaleTarget->SetRenderScale(FVector2D(TargetScale, TargetScale)); } else diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/StoreWidget.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/StoreWidget.cpp index f91ecffd..49739211 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/StoreWidget.cpp +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/StoreWidget.cpp @@ -16,95 +16,18 @@ #include "Widgets/StoreWidget.h" -#include "Actors/TrivialKartHUD.h" -#include "Blueprint/WidgetTree.h" -#include "Components/Border.h" -#include "Components/Button.h" #include "Components/CheckBox.h" -#include "Components/HorizontalBox.h" -#include "Components/Image.h" -#include "Components/Overlay.h" -#include "Components/OverlaySlot.h" -#include "Components/PanelWidget.h" -#include "Components/ScrollBox.h" -#include "Components/TextBlock.h" -#include "Components/VerticalBox.h" -#include "Components/WidgetSwitcher.h" -#include "Widgets/SelectableItem.h" -static UBorder* EnsureTabHighlightBorder(UWidgetTree* WidgetTree, UCheckBox* CB) +void UStoreWidget::RegisterTabCheckBoxes(TArray& OutCheckBoxes) { - UOverlay* ParentOverlay = CB ? Cast(CB->GetParent()) : nullptr; - if (!WidgetTree || !ParentOverlay) - { - return nullptr; - } - - UBorder* Border = WidgetTree->ConstructWidget(UBorder::StaticClass()); - Border->SetVisibility(ESlateVisibility::Collapsed); - Border->SetPadding(FMargin(0.0f)); - if (UOverlaySlot* OverlaySlot = ParentOverlay->AddChildToOverlay(Border)) - { - OverlaySlot->SetHorizontalAlignment(HAlign_Fill); - OverlaySlot->SetVerticalAlignment(VAlign_Fill); - } - return Border; + OutCheckBoxes.Add(FuelCheckBox); + OutCheckBoxes.Add(CoinCheckBox); + OutCheckBoxes.Add(CarCheckBox); + OutCheckBoxes.Add(SubscriptionCheckBox); } -void UStoreWidget::NativeConstruct() +void UStoreWidget::BindTabCheckBoxEvents() { - Super::NativeConstruct(); - - // Keep the modal root hit-testable so empty modal space blocks clicks from piercing into FSceneViewport - SetVisibility(ESlateVisibility::Visible); - - if (WidgetTree) - { - UWidget* TreeRoot = WidgetTree->RootWidget; - WidgetTree->ForEachWidget([TreeRoot](UWidget* Widget) - { - if (!Widget || Widget == TreeRoot || Widget->GetVisibility() != ESlateVisibility::Visible) - { - return; - } - if (Cast(Widget) || Cast(Widget)) - { - Widget->SetVisibility(ESlateVisibility::HitTestInvisible); - } - else if (Cast(Widget) || Cast(Widget) || Cast(Widget)) - { - Widget->SetVisibility(ESlateVisibility::SelfHitTestInvisible); - } - }); - } - - if (BackButton) - { - if (!bBackStyleCached) - { - OriginalBackButtonStyle = BackButton->GetStyle(); - OriginalBackButtonBgColor = BackButton->GetBackgroundColor(); - bBackStyleCached = true; - } - BackButton->OnClicked.AddUniqueDynamic(this, &UStoreWidget::OnBackButtonClicked); - BackButton->OnReleased.AddUniqueDynamic(this, &UStoreWidget::OnBackButtonReleased); - } - - CheckBoxes.Empty(); - CheckBoxes.Add(FuelCheckBox); - CheckBoxes.Add(CoinCheckBox); - CheckBoxes.Add(CarCheckBox); - CheckBoxes.Add(SubscriptionCheckBox); - - if (TabHighlightBorders.Num() != CheckBoxes.Num()) - { - TabHighlightBorders.Empty(); - for (UCheckBox* CB : CheckBoxes) - { - TabHighlightBorders.Add(EnsureTabHighlightBorder(WidgetTree, CB)); - } - } - if (FuelCheckBox) { FuelCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UStoreWidget::OnFuelBoxStateChanged); @@ -121,29 +44,10 @@ void UStoreWidget::NativeConstruct() { SubscriptionCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UStoreWidget::OnSubscriptionBoxStateChange); } - - if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) - { - PC->OnInputModeUpdated.RemoveAll(this); - PC->OnInputModeUpdated.AddUObject(this, &UStoreWidget::OnInputModeChanged); - } - - GamepadPressedItem.Reset(); - HoveredItem.Reset(); - bBackButtonPressed = false; - RefreshAllItemsOwnership(); - ActiveTabIndex = ContentSwitcher ? ContentSwitcher->GetActiveWidgetIndex() : 0; - FocusedItemIndex = 0; - RefreshGamepadFocus(false); } -void UStoreWidget::NativeDestruct() +void UStoreWidget::UnbindTabCheckBoxEvents() { - if (BackButton) - { - BackButton->OnClicked.RemoveDynamic(this, &UStoreWidget::OnBackButtonClicked); - BackButton->OnReleased.RemoveDynamic(this, &UStoreWidget::OnBackButtonReleased); - } if (FuelCheckBox) { FuelCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UStoreWidget::OnFuelBoxStateChanged); @@ -160,524 +64,6 @@ void UStoreWidget::NativeDestruct() { SubscriptionCheckBox->OnCheckStateChanged.RemoveDynamic(this, &UStoreWidget::OnSubscriptionBoxStateChange); } - - if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) - { - PC->OnInputModeUpdated.RemoveAll(this); - } - - CheckBoxes.Empty(); - Super::NativeDestruct(); -} - -bool UStoreWidget::IsNavigationVisualActive() const -{ - if (const ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) - { - return PC->IsKeyNavigationActive(); - } - return false; -} - -void UStoreWidget::RestoreViewportFocus() const -{ - if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) - { - PC->RestoreFocusToGameViewport(); - } -} - -void UStoreWidget::OnInputModeChanged(ETrivialKartInputMode NewInputMode) -{ - if (!IsNavigationVisualActive()) - { - CancelPendingPress(); - } - RefreshGamepadFocus(false); -} - -void UStoreWidget::OnBackButtonReleased() -{ - RestoreViewportFocus(); -} - -void UStoreWidget::OnBackButtonClicked() -{ - if (TWeakObjectPtr PlayerController = GetOwningPlayer(); PlayerController.IsValid()) - { - if (const TWeakObjectPtr CurrentHUD = Cast(PlayerController->GetHUD()); - CurrentHUD.IsValid()) - { - CurrentHUD->AddWidgetToScreen(EWidgetType::PlayBoard); - CurrentHUD->RemoveWidgetFromScreen(EWidgetType::Store); - } - } -} - -void UStoreWidget::SetCheckBoxState(bool bIsChecked, UCheckBox* CheckBox, int ActiveWidgetIndex) -{ - if (CheckBox == nullptr) - { - return; - } - CancelPendingPress(); - HoveredItem.Reset(); - FocusedItemIndex = -1; - if (bIsChecked) - { - ActiveTabIndex = ActiveWidgetIndex; - if (ContentSwitcher) - { - ContentSwitcher->SetActiveWidgetIndex(ActiveWidgetIndex); - } - for (auto CurrentCheckBox : CheckBoxes) - { - if (CurrentCheckBox && CurrentCheckBox != CheckBox) - { - CurrentCheckBox->SetCheckedState(ECheckBoxState::Unchecked); - } - } - } - else - { - CheckBox->SetCheckedState(ECheckBoxState::Checked); - } - RefreshAllItemsOwnership(); - RefreshGamepadFocus(false); - RestoreViewportFocus(); -} - -void UStoreWidget::SelectTabByIndex(int32 NewTabIndex) -{ - if (CheckBoxes.Num() == 0) - { - return; - } - ActiveTabIndex = (NewTabIndex + CheckBoxes.Num()) % CheckBoxes.Num(); - if (UCheckBox* TargetCheckBox = CheckBoxes[ActiveTabIndex]) - { - TargetCheckBox->SetCheckedState(ECheckBoxState::Checked); - SetCheckBoxState(true, TargetCheckBox, ActiveTabIndex); - } -} - -void UStoreWidget::RefreshAllItemsOwnership() const -{ - TArray AllItems; - GatherSelectableItems(ContentSwitcher, AllItems, false); - for (USelectableItem* Item : AllItems) - { - if (Item) - { - Item->RefreshOwnershipState(); - } - } -} - -void UStoreWidget::GatherSelectableItems(UWidget* RootWidget, TArray& OutItems, bool bOnlySelectable) const -{ - if (!RootWidget) - { - return; - } - if (USelectableItem* Item = Cast(RootWidget)) - { - if (!bOnlySelectable || Item->IsItemSelectable()) - { - OutItems.Add(Item); - } - return; - } - if (bOnlySelectable && !RootWidget->IsVisible()) - { - return; - } - if (UPanelWidget* Panel = Cast(RootWidget)) - { - for (int32 i = 0; i < Panel->GetChildrenCount(); ++i) - { - GatherSelectableItems(Panel->GetChildAt(i), OutItems, bOnlySelectable); - } - } -} - -void UStoreWidget::OnSelectableItemInteracted(USelectableItem* InteractedItem) -{ - HoveredItem = InteractedItem; - TArray ActiveItems; - if (ContentSwitcher) - { - GatherSelectableItems(ContentSwitcher->GetActiveWidget(), ActiveItems, true); - } - const int32 FoundIndex = ActiveItems.IndexOfByKey(InteractedItem); - if (FoundIndex != INDEX_NONE) - { - FocusedItemIndex = FoundIndex; - } - RefreshGamepadFocus(false); -} - -void UStoreWidget::OnSelectableItemUnhovered(USelectableItem* UnhoveredItem) -{ - if (HoveredItem.Get() == UnhoveredItem) - { - HoveredItem.Reset(); - if (!IsNavigationVisualActive()) - { - RefreshGamepadFocus(false); - } - } -} - -void UStoreWidget::OnSelectableItemClicked(USelectableItem* ClickedItem) -{ - RefreshAllItemsOwnership(); - if (ClickedItem && !ClickedItem->IsItemSelectable()) - { - HoveredItem.Reset(); - RefreshGamepadFocus(false); - } - else - { - OnSelectableItemInteracted(ClickedItem); - } -} - -void UStoreWidget::RefreshOwnershipAndFocus(bool bScrollIntoView) -{ - RefreshAllItemsOwnership(); - RefreshGamepadFocus(bScrollIntoView); -} - -void UStoreWidget::CancelPendingPress() -{ - if (USelectableItem* PressedItem = GamepadPressedItem.Get()) - { - PressedItem->SetButtonPressed(false); - } - GamepadPressedItem.Reset(); - if (bBackButtonPressed) - { - bBackButtonPressed = false; - RefreshGamepadFocus(false); - } -} - -void UStoreWidget::RefreshGamepadFocus(bool bScrollIntoView) -{ - const ATrivialKartPlayerController* PC = Cast(GetOwningPlayer()); - const bool bShowNavVisual = IsNavigationVisualActive(); - const bool bAllowMouseHoverVisual = (!bShowNavVisual && PC && PC->GetActiveInputMode() == ETrivialKartInputMode::KeyboardMouse); - - TArray ActiveItems; - if (ContentSwitcher) - { - GatherSelectableItems(ContentSwitcher->GetActiveWidget(), ActiveItems, true); - } - - USelectableItem* FocusedItem = nullptr; - if (ActiveItems.Num() == 0 && FocusedItemIndex >= 0) - { - FocusedItemIndex = -1; - } - else if (FocusedItemIndex >= 0) - { - FocusedItemIndex = FMath::Clamp(FocusedItemIndex, 0, ActiveItems.Num() - 1); - FocusedItem = ActiveItems[FocusedItemIndex]; - } - - TArray AllItems; - GatherSelectableItems(ContentSwitcher, AllItems, false); - for (USelectableItem* Item : AllItems) - { - if (Item) - { - const bool bIsInActiveTab = ActiveItems.Contains(Item); - Item->OnItemInteracted.BindUObject(this, &UStoreWidget::OnSelectableItemInteracted); - Item->OnItemUnhovered.BindUObject(this, &UStoreWidget::OnSelectableItemUnhovered); - Item->OnItemClicked.BindUObject(this, &UStoreWidget::OnSelectableItemClicked); - if (!bIsInActiveTab || (Item != GamepadPressedItem.Get() && !Item->IsButtonHovered())) - { - Item->SetButtonPressed(false); - } - const bool bIsHoveredByMouse = (bAllowMouseHoverVisual && bIsInActiveTab && HoveredItem.Get() == Item && Item->IsButtonHovered()); - const bool bIsFocusedTarget = bShowNavVisual ? (Item == FocusedItem) : bIsHoveredByMouse; - Item->SetGamepadFocused(bIsFocusedTarget, bShowNavVisual || bIsHoveredByMouse); - } - } - - if (FocusedItem && bScrollIntoView && bShowNavVisual) - { - for (UPanelWidget* Parent = FocusedItem->GetParent(); Parent != nullptr; Parent = Parent->GetParent()) - { - if (UScrollBox* ScrollBox = Cast(Parent)) - { - ScrollBox->ScrollWidgetIntoView(FocusedItem, true, EDescendantScrollDestination::IntoView); - break; - } - } - } - - if (BackButton && bBackStyleCached) - { - const bool bBackFocused = bShowNavVisual && (FocusedItemIndex == -2); - BackButton->SetRenderTransformPivot(FVector2D(0.5f, 0.5f)); - if (bBackFocused) - { - const bool bPressed = bBackButtonPressed || BackButton->IsPressed(); - FSlateBrush HighlightBrush; - HighlightBrush.DrawAs = ESlateBrushDrawType::RoundedBox; - HighlightBrush.TintColor = FSlateColor(bPressed - ? FLinearColor(1.0f, 0.35f, 0.0f, 0.68f) - : FLinearColor(1.0f, 0.45f, 0.0f, 0.48f)); - HighlightBrush.OutlineSettings.CornerRadii = FVector4(10.0f, 10.0f, 10.0f, 10.0f); - HighlightBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; - HighlightBrush.OutlineSettings.Color = FSlateColor(FLinearColor(1.0f, 0.9f, 0.0f, 1.0f)); - HighlightBrush.OutlineSettings.Width = 6.0f; - - FButtonStyle FocusedStyle = OriginalBackButtonStyle; - FocusedStyle.SetNormal(HighlightBrush); - FocusedStyle.SetHovered(HighlightBrush); - FocusedStyle.SetPressed(HighlightBrush); - BackButton->SetStyle(FocusedStyle); - BackButton->SetBackgroundColor(FLinearColor::White); - BackButton->SetRenderScale(FVector2D(bPressed ? 0.88f : 1.12f, bPressed ? 0.88f : 1.12f)); - } - else - { - BackButton->SetStyle(OriginalBackButtonStyle); - BackButton->SetBackgroundColor(OriginalBackButtonBgColor); - BackButton->SetRenderScale(FVector2D(1.0f, 1.0f)); - } - } - - const bool bTabBarFocused = bShowNavVisual && (FocusedItemIndex == -1); - for (int32 i = 0; i < CheckBoxes.Num(); ++i) - { - UCheckBox* CB = CheckBoxes[i]; - UBorder* HighlightBorder = TabHighlightBorders.IsValidIndex(i) ? TabHighlightBorders[i].Get() : nullptr; - if (!CB) - { - continue; - } - UWidget* TabScaleTarget = CB->GetParent() - ? static_cast(CB->GetParent()) - : static_cast(CB); - TabScaleTarget->SetRenderTransformPivot(FVector2D(0.5f, 0.5f)); - if (i == ActiveTabIndex) - { - if (HighlightBorder) - { - FSlateBrush OverlayBrush; - OverlayBrush.DrawAs = ESlateBrushDrawType::RoundedBox; - OverlayBrush.ImageSize = CB->GetWidgetStyle().CheckedImage.ImageSize; - OverlayBrush.TintColor = FSlateColor(FLinearColor(1.0f, 0.45f, 0.0f, 0.48f)); - OverlayBrush.OutlineSettings.CornerRadii = FVector4(8.0f, 8.0f, 8.0f, 8.0f); - OverlayBrush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; - OverlayBrush.OutlineSettings.Color = FSlateColor(bTabBarFocused - ? FLinearColor(1.0f, 0.9f, 0.0f, 1.0f) - : FLinearColor::Transparent); - OverlayBrush.OutlineSettings.Width = bTabBarFocused ? 6.0f : 0.0f; - HighlightBorder->SetBrush(OverlayBrush); - HighlightBorder->SetBrushColor(FLinearColor::White); - HighlightBorder->SetVisibility(ESlateVisibility::HitTestInvisible); - } - const float TargetTabScale = bTabBarFocused ? 1.15f : 1.0f; - TabScaleTarget->SetRenderScale(FVector2D(TargetTabScale, TargetTabScale)); - } - else - { - if (HighlightBorder) - { - HighlightBorder->SetVisibility(ESlateVisibility::Collapsed); - } - TabScaleTarget->SetRenderScale(FVector2D(1.0f, 1.0f)); - } - } -} - -bool UStoreWidget::HandleGamepadKey(const FKey& Key, bool bIsPressed) -{ - if (!bIsPressed) - { - if (Key == EKeys::Gamepad_FaceButton_Bottom) - { - if (bBackButtonPressed) - { - bBackButtonPressed = false; - RefreshGamepadFocus(false); - if (FocusedItemIndex == -2) - { - OnBackButtonClicked(); - } - return true; - } - - USelectableItem* PreviouslyPressed = GamepadPressedItem.Get(); - GamepadPressedItem.Reset(); - - TArray ActiveItems; - if (ContentSwitcher) - { - GatherSelectableItems(ContentSwitcher->GetActiveWidget(), ActiveItems, true); - } - if (PreviouslyPressed && FocusedItemIndex >= 0 && FocusedItemIndex < ActiveItems.Num() && - ActiveItems[FocusedItemIndex] == PreviouslyPressed) - { - PreviouslyPressed->SetButtonPressed(false); - PreviouslyPressed->OnSelectionButtonClicked(); - } - else if (PreviouslyPressed) - { - PreviouslyPressed->SetButtonPressed(false); - } - return true; - } - return false; - } - - if (Key == EKeys::Gamepad_FaceButton_Right) - { - CancelPendingPress(); - OnBackButtonClicked(); - return true; - } - if (Key == EKeys::Gamepad_LeftShoulder) - { - SelectTabByIndex(ActiveTabIndex - 1); - return true; - } - if (Key == EKeys::Gamepad_RightShoulder) - { - SelectTabByIndex(ActiveTabIndex + 1); - return true; - } - - TArray ActiveItems; - if (ContentSwitcher) - { - GatherSelectableItems(ContentSwitcher->GetActiveWidget(), ActiveItems, true); - } - - // If opened via touch/mouse with navigation focus hidden, reveal focus on the first navigation/confirm press - if (!IsNavigationVisualActive()) - { - if (Key == EKeys::Gamepad_DPad_Left || Key == EKeys::Gamepad_DPad_Right || - Key == EKeys::Gamepad_DPad_Up || Key == EKeys::Gamepad_DPad_Down || - Key == EKeys::Gamepad_FaceButton_Bottom) - { - CancelPendingPress(); - if (Key == EKeys::Gamepad_DPad_Up || ActiveItems.Num() == 0) - { - FocusedItemIndex = -1; - } - else if (FocusedItemIndex < 0) - { - FocusedItemIndex = 0; - } - if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) - { - PC->SetKeyNavigationActive(true); - } - RefreshGamepadFocus(true); - return true; - } - } - - if (Key == EKeys::Gamepad_DPad_Left) - { - CancelPendingPress(); - if (FocusedItemIndex == -2) - { - RefreshGamepadFocus(false); - } - else if (FocusedItemIndex == -1) - { - SelectTabByIndex(ActiveTabIndex - 1); - } - else if (ActiveItems.Num() > 1) - { - FocusedItemIndex = (FocusedItemIndex + ActiveItems.Num() - 1) % ActiveItems.Num(); - RefreshGamepadFocus(); - } - else - { - RefreshGamepadFocus(); - } - return true; - } - if (Key == EKeys::Gamepad_DPad_Right) - { - CancelPendingPress(); - if (FocusedItemIndex == -2) - { - RefreshGamepadFocus(false); - } - else if (FocusedItemIndex == -1) - { - SelectTabByIndex(ActiveTabIndex + 1); - } - else if (ActiveItems.Num() > 1) - { - FocusedItemIndex = (FocusedItemIndex + 1) % ActiveItems.Num(); - RefreshGamepadFocus(); - } - else - { - RefreshGamepadFocus(); - } - return true; - } - if (Key == EKeys::Gamepad_DPad_Up) - { - CancelPendingPress(); - if (FocusedItemIndex >= 0) - { - FocusedItemIndex = -1; - } - else if (FocusedItemIndex == -1 && BackButton) - { - FocusedItemIndex = -2; - } - RefreshGamepadFocus(false); - return true; - } - if (Key == EKeys::Gamepad_DPad_Down) - { - CancelPendingPress(); - if (FocusedItemIndex == -2) - { - FocusedItemIndex = -1; - } - else if (FocusedItemIndex == -1 && ActiveItems.Num() > 0) - { - FocusedItemIndex = 0; - } - RefreshGamepadFocus(); - return true; - } - if (Key == EKeys::Gamepad_FaceButton_Bottom) - { - if (FocusedItemIndex == -2 && BackButton) - { - bBackButtonPressed = true; - RefreshGamepadFocus(false); - } - else if (FocusedItemIndex >= 0 && FocusedItemIndex < ActiveItems.Num()) - { - GamepadPressedItem = ActiveItems[FocusedItemIndex]; - GamepadPressedItem->SetButtonPressed(true); - } - else if (FocusedItemIndex == -1 && ActiveItems.Num() > 0) - { - GamepadPressedItem.Reset(); - FocusedItemIndex = 0; - RefreshGamepadFocus(); - } - return true; - } - - return false; } void UStoreWidget::OnFuelBoxStateChanged(bool bIsChecked) diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/TrivialKartTabbedModalWidget.cpp b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/TrivialKartTabbedModalWidget.cpp new file mode 100644 index 00000000..28664f54 --- /dev/null +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Private/Widgets/TrivialKartTabbedModalWidget.cpp @@ -0,0 +1,705 @@ +/* +* Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "Widgets/TrivialKartTabbedModalWidget.h" + +#include "Blueprint/WidgetTree.h" +#include "Components/Border.h" +#include "Components/Button.h" +#include "Components/CheckBox.h" +#include "Components/Overlay.h" +#include "Components/OverlaySlot.h" +#include "Components/PanelWidget.h" +#include "Components/ScrollBox.h" +#include "Components/WidgetSwitcher.h" +#include "Widgets/SelectableItem.h" +#include "Widgets/TrivialKartUIStyle.h" + +namespace +{ + UBorder* EnsureModalTabHighlightBorder(UWidgetTree* WidgetTree, UCheckBox* CB) + { + UOverlay* ParentOverlay = CB ? Cast(CB->GetParent()) : nullptr; + if (!WidgetTree || !ParentOverlay) + { + return nullptr; + } + + UBorder* Border = WidgetTree->ConstructWidget(UBorder::StaticClass()); + Border->SetVisibility(ESlateVisibility::Collapsed); + Border->SetPadding(FMargin(0.0f)); + if (UOverlaySlot* OverlaySlot = ParentOverlay->AddChildToOverlay(Border)) + { + OverlaySlot->SetHorizontalAlignment(HAlign_Fill); + OverlaySlot->SetVerticalAlignment(VAlign_Fill); + } + return Border; + } +} + +void UTrivialKartTabbedModalWidget::ConfigureModalHitTesting() +{ + if (WidgetTree) + { + TrivialKartUIStyle::NormalizeWidgetTreeHitTesting(WidgetTree, WidgetTree->RootWidget); + } +} + +void UTrivialKartTabbedModalWidget::CacheAndBindSelectableItems() +{ + UnbindSelectableItems(); + if (!ContentSwitcher) + { + return; + } + + const int32 NumTabs = ContentSwitcher->GetChildrenCount(); + CachedItemsByTab.SetNum(NumTabs); + for (int32 TabIdx = 0; TabIdx < NumTabs; ++TabIdx) + { + TArray TabItems; + GatherSelectableItems(ContentSwitcher->GetChildAt(TabIdx), TabItems, false); + for (USelectableItem* Item : TabItems) + { + if (Item) + { + Item->OnItemInteracted.BindUObject(this, &UTrivialKartTabbedModalWidget::OnSelectableItemInteracted); + Item->OnItemUnhovered.BindUObject(this, &UTrivialKartTabbedModalWidget::OnSelectableItemUnhovered); + Item->OnItemClicked.BindUObject(this, &UTrivialKartTabbedModalWidget::OnSelectableItemClicked); + CachedItemsByTab[TabIdx].Add(Item); + CachedAllItems.Add(Item); + } + } + } +} + +void UTrivialKartTabbedModalWidget::UnbindSelectableItems() +{ + for (const TWeakObjectPtr& WeakItem : CachedAllItems) + { + if (USelectableItem* Item = WeakItem.Get()) + { + Item->OnItemInteracted.Unbind(); + Item->OnItemUnhovered.Unbind(); + Item->OnItemClicked.Unbind(); + } + } + CachedItemsByTab.Empty(); + CachedAllItems.Empty(); +} + +void UTrivialKartTabbedModalWidget::NativeConstruct() +{ + Super::NativeConstruct(); + + // Keep the modal root hit-testable so empty modal space blocks clicks from piercing into FSceneViewport + SetVisibility(ESlateVisibility::Visible); + ConfigureModalHitTesting(); + + if (BackButton) + { + if (!bBackStyleCached) + { + OriginalBackButtonStyle = BackButton->GetStyle(); + OriginalBackButtonBgColor = BackButton->GetBackgroundColor(); + bBackStyleCached = true; + } + BackButton->OnClicked.AddUniqueDynamic(this, &UTrivialKartTabbedModalWidget::OnBackButtonClicked); + BackButton->OnReleased.AddUniqueDynamic(this, &UTrivialKartTabbedModalWidget::OnBackButtonReleased); + } + + CheckBoxes.Empty(); + RegisterTabCheckBoxes(CheckBoxes); + + if (TabHighlightBorders.Num() != CheckBoxes.Num()) + { + TabHighlightBorders.Empty(); + for (UCheckBox* CB : CheckBoxes) + { + TabHighlightBorders.Add(EnsureModalTabHighlightBorder(WidgetTree, CB)); + } + } + + BindTabCheckBoxEvents(); + InitializeModalContent(); + CacheAndBindSelectableItems(); + + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->OnInputModeUpdated.RemoveAll(this); + PC->OnInputModeUpdated.AddUObject(this, &UTrivialKartTabbedModalWidget::OnInputModeChanged); + } + + GamepadPressedItem.Reset(); + HoveredItem.Reset(); + bBackButtonPressed = false; + RefreshAllItemsOwnership(); + ActiveTabIndex = ContentSwitcher ? ContentSwitcher->GetActiveWidgetIndex() : 0; + + TArray ActiveItems; + GetActiveSelectableItems(ActiveItems); + FocusedItemIndex = (ActiveItems.Num() > 0) + ? GetDefaultItemIndexForTab(ActiveTabIndex, ActiveItems) + : -1; + RefreshGamepadFocus(IsNavigationVisualActive()); +} + +void UTrivialKartTabbedModalWidget::NativeDestruct() +{ + if (BackButton) + { + BackButton->OnClicked.RemoveDynamic(this, &UTrivialKartTabbedModalWidget::OnBackButtonClicked); + BackButton->OnReleased.RemoveDynamic(this, &UTrivialKartTabbedModalWidget::OnBackButtonReleased); + } + + UnbindTabCheckBoxEvents(); + UnbindSelectableItems(); + + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->OnInputModeUpdated.RemoveAll(this); + } + + CheckBoxes.Empty(); + Super::NativeDestruct(); +} + +bool UTrivialKartTabbedModalWidget::IsNavigationVisualActive() const +{ + if (const ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + return PC->IsKeyNavigationActive(); + } + return false; +} + +void UTrivialKartTabbedModalWidget::RestoreViewportFocus() const +{ + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->RestoreFocusToGameViewport(); + } +} + +void UTrivialKartTabbedModalWidget::OnInputModeChanged(ETrivialKartInputMode NewInputMode) +{ + if (!IsNavigationVisualActive()) + { + CancelPendingPress(); + } + RefreshGamepadFocus(false); +} + +void UTrivialKartTabbedModalWidget::OnBackButtonReleased() +{ + RestoreViewportFocus(); +} + +void UTrivialKartTabbedModalWidget::OnBackButtonClicked() +{ + if (TWeakObjectPtr PlayerController = GetOwningPlayer(); PlayerController.IsValid()) + { + if (const TWeakObjectPtr CurrentHUD = Cast(PlayerController->GetHUD()); + CurrentHUD.IsValid()) + { + CurrentHUD->AddWidgetToScreen(EWidgetType::PlayBoard); + const EWidgetType ModalType = GetModalWidgetType(); + if (ModalType != EWidgetType::None) + { + CurrentHUD->RemoveWidgetFromScreen(ModalType); + } + } + } +} + +void UTrivialKartTabbedModalWidget::SetCheckBoxState(bool bIsChecked, UCheckBox* CheckBox, int32 ActiveWidgetIndex) +{ + if (CheckBox == nullptr) + { + return; + } + CancelPendingPress(); + HoveredItem.Reset(); + FocusedItemIndex = -1; + if (bIsChecked) + { + ActiveTabIndex = ActiveWidgetIndex; + if (ContentSwitcher) + { + ContentSwitcher->SetActiveWidgetIndex(ActiveWidgetIndex); + } + for (UCheckBox* CurrentCheckBox : CheckBoxes) + { + if (CurrentCheckBox && CurrentCheckBox != CheckBox) + { + CurrentCheckBox->SetCheckedState(ECheckBoxState::Unchecked); + } + } + } + else + { + CheckBox->SetCheckedState(ECheckBoxState::Checked); + } + RefreshAllItemsOwnership(); + RefreshGamepadFocus(false); + RestoreViewportFocus(); +} + +void UTrivialKartTabbedModalWidget::SelectTabByIndex(int32 NewTabIndex) +{ + if (CheckBoxes.Num() == 0) + { + return; + } + ActiveTabIndex = (NewTabIndex + CheckBoxes.Num()) % CheckBoxes.Num(); + if (UCheckBox* TargetCheckBox = CheckBoxes[ActiveTabIndex]) + { + TargetCheckBox->SetCheckedState(ECheckBoxState::Checked); + SetCheckBoxState(true, TargetCheckBox, ActiveTabIndex); + } +} + +void UTrivialKartTabbedModalWidget::RefreshAllItemsOwnership() const +{ + for (const TWeakObjectPtr& WeakItem : CachedAllItems) + { + if (USelectableItem* Item = WeakItem.Get()) + { + Item->RefreshOwnershipState(); + } + } +} + +void UTrivialKartTabbedModalWidget::GetActiveSelectableItems(TArray& OutItems) const +{ + OutItems.Reset(); + if (!ContentSwitcher) + { + return; + } + const int32 TabIdx = ContentSwitcher->GetActiveWidgetIndex(); + if (!CachedItemsByTab.IsValidIndex(TabIdx)) + { + return; + } + for (const TWeakObjectPtr& WeakItem : CachedItemsByTab[TabIdx]) + { + if (USelectableItem* Item = WeakItem.Get(); Item && Item->IsItemSelectable()) + { + OutItems.Add(Item); + } + } +} + +void UTrivialKartTabbedModalWidget::GatherSelectableItems(UWidget* RootWidget, TArray& OutItems, bool bOnlySelectable) const +{ + if (!RootWidget) + { + return; + } + if (USelectableItem* Item = Cast(RootWidget)) + { + if (!bOnlySelectable || Item->IsItemSelectable()) + { + OutItems.Add(Item); + } + return; + } + if (bOnlySelectable && !RootWidget->IsVisible()) + { + return; + } + if (UPanelWidget* Panel = Cast(RootWidget)) + { + for (int32 i = 0; i < Panel->GetChildrenCount(); ++i) + { + GatherSelectableItems(Panel->GetChildAt(i), OutItems, bOnlySelectable); + } + } +} + +void UTrivialKartTabbedModalWidget::OnSelectableItemInteracted(USelectableItem* InteractedItem) +{ + HoveredItem = InteractedItem; + TArray ActiveItems; + GetActiveSelectableItems(ActiveItems); + const int32 FoundIndex = ActiveItems.IndexOfByKey(InteractedItem); + if (FoundIndex != INDEX_NONE) + { + FocusedItemIndex = FoundIndex; + } + RefreshGamepadFocus(false); +} + +void UTrivialKartTabbedModalWidget::OnSelectableItemUnhovered(USelectableItem* UnhoveredItem) +{ + if (HoveredItem.Get() == UnhoveredItem) + { + HoveredItem.Reset(); + if (!IsNavigationVisualActive()) + { + RefreshGamepadFocus(false); + } + } +} + +void UTrivialKartTabbedModalWidget::OnSelectableItemClicked(USelectableItem* ClickedItem) +{ + RefreshAllItemsOwnership(); + if (ClickedItem && !ClickedItem->IsItemSelectable()) + { + HoveredItem.Reset(); + RefreshGamepadFocus(false); + } + else + { + OnSelectableItemInteracted(ClickedItem); + } +} + +void UTrivialKartTabbedModalWidget::RefreshOwnershipAndFocus(bool bScrollIntoView) +{ + RefreshAllItemsOwnership(); + RefreshGamepadFocus(bScrollIntoView); +} + +void UTrivialKartTabbedModalWidget::CancelPendingPress() +{ + if (USelectableItem* PressedItem = GamepadPressedItem.Get()) + { + PressedItem->SetButtonPressed(false); + } + GamepadPressedItem.Reset(); + if (bBackButtonPressed) + { + bBackButtonPressed = false; + RefreshGamepadFocus(false); + } +} + +void UTrivialKartTabbedModalWidget::RefreshGamepadFocus(bool bScrollIntoView) +{ + const ATrivialKartPlayerController* PC = Cast(GetOwningPlayer()); + const bool bShowNavVisual = IsNavigationVisualActive(); + const bool bAllowMouseHoverVisual = (!bShowNavVisual && PC && PC->GetActiveInputMode() == ETrivialKartInputMode::KeyboardMouse); + + TArray ActiveItems; + GetActiveSelectableItems(ActiveItems); + + USelectableItem* FocusedItem = nullptr; + if (ActiveItems.Num() == 0 && FocusedItemIndex >= 0) + { + FocusedItemIndex = -1; + } + else if (FocusedItemIndex >= 0) + { + FocusedItemIndex = FMath::Clamp(FocusedItemIndex, 0, ActiveItems.Num() - 1); + FocusedItem = ActiveItems[FocusedItemIndex]; + } + + const int32 CurrentTabIdx = ContentSwitcher ? ContentSwitcher->GetActiveWidgetIndex() : INDEX_NONE; + for (int32 TabIdx = 0; TabIdx < CachedItemsByTab.Num(); ++TabIdx) + { + const bool bIsInActiveTab = (TabIdx == CurrentTabIdx); + for (const TWeakObjectPtr& WeakItem : CachedItemsByTab[TabIdx]) + { + if (USelectableItem* Item = WeakItem.Get()) + { + if (!bIsInActiveTab || (Item != GamepadPressedItem.Get() && !Item->IsButtonHovered())) + { + Item->SetButtonPressed(false); + } + const bool bIsHoveredByMouse = (bAllowMouseHoverVisual && bIsInActiveTab && HoveredItem.Get() == Item && Item->IsButtonHovered()); + const bool bIsFocusedTarget = bShowNavVisual ? (Item == FocusedItem) : bIsHoveredByMouse; + Item->SetGamepadFocused(bIsFocusedTarget, bShowNavVisual || bIsHoveredByMouse); + } + } + } + + if (FocusedItem && bScrollIntoView && bShowNavVisual) + { + for (UPanelWidget* Parent = FocusedItem->GetParent(); Parent != nullptr; Parent = Parent->GetParent()) + { + if (UScrollBox* ScrollBox = Cast(Parent)) + { + ScrollBox->ScrollWidgetIntoView(FocusedItem, true, EDescendantScrollDestination::IntoView); + break; + } + } + } + + if (BackButton && bBackStyleCached) + { + const bool bBackFocused = bShowNavVisual && (FocusedItemIndex == -2); + BackButton->SetRenderTransformPivot(FVector2D(0.5f, 0.5f)); + if (bBackFocused) + { + const bool bPressed = bBackButtonPressed || BackButton->IsPressed(); + const FSlateBrush HighlightBrush = TrivialKartUIStyle::MakeButtonFocusBrush(bPressed, 10.0f); + + FButtonStyle FocusedStyle = OriginalBackButtonStyle; + FocusedStyle.SetNormal(HighlightBrush); + FocusedStyle.SetHovered(HighlightBrush); + FocusedStyle.SetPressed(HighlightBrush); + BackButton->SetStyle(FocusedStyle); + BackButton->SetBackgroundColor(FLinearColor::White); + BackButton->SetRenderScale(FVector2D(bPressed ? 0.88f : 1.12f, bPressed ? 0.88f : 1.12f)); + } + else + { + BackButton->SetStyle(OriginalBackButtonStyle); + BackButton->SetBackgroundColor(OriginalBackButtonBgColor); + BackButton->SetRenderScale(FVector2D(1.0f, 1.0f)); + } + } + + const bool bTabBarFocused = bShowNavVisual && (FocusedItemIndex == -1); + for (int32 i = 0; i < CheckBoxes.Num(); ++i) + { + UCheckBox* CB = CheckBoxes[i]; + UBorder* HighlightBorder = TabHighlightBorders.IsValidIndex(i) ? TabHighlightBorders[i].Get() : nullptr; + if (!CB) + { + continue; + } + UWidget* TabScaleTarget = CB->GetParent() + ? static_cast(CB->GetParent()) + : static_cast(CB); + TabScaleTarget->SetRenderTransformPivot(FVector2D(0.5f, 0.5f)); + if (i == ActiveTabIndex) + { + if (HighlightBorder) + { + const FSlateBrush OverlayBrush = TrivialKartUIStyle::MakeRoundedHighlightBrush( + 8.0f, + bTabBarFocused ? 6.0f : 0.0f, + FLinearColor(1.0f, 0.45f, 0.0f, 0.48f), + bTabBarFocused ? FLinearColor(1.0f, 0.9f, 0.0f, 1.0f) : FLinearColor::Transparent, + CB->GetWidgetStyle().CheckedImage.ImageSize); + HighlightBorder->SetBrush(OverlayBrush); + HighlightBorder->SetBrushColor(FLinearColor::White); + HighlightBorder->SetVisibility(ESlateVisibility::HitTestInvisible); + } + const float TargetTabScale = bTabBarFocused ? 1.15f : 1.0f; + TabScaleTarget->SetRenderScale(FVector2D(TargetTabScale, TargetTabScale)); + } + else + { + if (HighlightBorder) + { + HighlightBorder->SetVisibility(ESlateVisibility::Collapsed); + } + TabScaleTarget->SetRenderScale(FVector2D(1.0f, 1.0f)); + } + } +} + +bool UTrivialKartTabbedModalWidget::HandleGamepadKey(const FKey& Key, bool bIsPressed) +{ + if (!bIsPressed) + { + if (Key == EKeys::Gamepad_FaceButton_Bottom) + { + if (bBackButtonPressed) + { + bBackButtonPressed = false; + RefreshGamepadFocus(false); + if (FocusedItemIndex == -2) + { + OnBackButtonClicked(); + } + return true; + } + + USelectableItem* PreviouslyPressed = GamepadPressedItem.Get(); + GamepadPressedItem.Reset(); + + TArray ActiveItems; + GetActiveSelectableItems(ActiveItems); + if (PreviouslyPressed && FocusedItemIndex >= 0 && FocusedItemIndex < ActiveItems.Num() && + ActiveItems[FocusedItemIndex] == PreviouslyPressed) + { + PreviouslyPressed->SetButtonPressed(false); + PreviouslyPressed->OnSelectionButtonClicked(); + } + else if (PreviouslyPressed) + { + PreviouslyPressed->SetButtonPressed(false); + } + return true; + } + return false; + } + + if (Key == EKeys::Gamepad_FaceButton_Right) + { + CancelPendingPress(); + OnBackButtonClicked(); + return true; + } + if (Key == EKeys::Gamepad_LeftShoulder) + { + SelectTabByIndex(ActiveTabIndex - 1); + return true; + } + if (Key == EKeys::Gamepad_RightShoulder) + { + SelectTabByIndex(ActiveTabIndex + 1); + return true; + } + + TArray ActiveItems; + GetActiveSelectableItems(ActiveItems); + + // If opened via touch/mouse with navigation focus hidden, reveal focus on the first navigation/confirm press + if (!IsNavigationVisualActive()) + { + if (Key == EKeys::Gamepad_DPad_Left || Key == EKeys::Gamepad_DPad_Right || + Key == EKeys::Gamepad_DPad_Up || Key == EKeys::Gamepad_DPad_Down || + Key == EKeys::Gamepad_FaceButton_Bottom) + { + CancelPendingPress(); + if (Key == EKeys::Gamepad_DPad_Up || ActiveItems.Num() == 0) + { + FocusedItemIndex = -1; + } + else if (FocusedItemIndex < 0) + { + FocusedItemIndex = GetDefaultItemIndexForTab(ActiveTabIndex, ActiveItems); + } + if (ATrivialKartPlayerController* PC = Cast(GetOwningPlayer())) + { + PC->SetKeyNavigationActive(true); + } + RefreshGamepadFocus(true); + return true; + } + } + + if (Key == EKeys::Gamepad_DPad_Left) + { + CancelPendingPress(); + if (FocusedItemIndex == -2) + { + RefreshGamepadFocus(false); + } + else if (FocusedItemIndex == -1) + { + SelectTabByIndex(ActiveTabIndex - 1); + } + else if (ActiveItems.Num() > 1) + { + FocusedItemIndex = (FocusedItemIndex + ActiveItems.Num() - 1) % ActiveItems.Num(); + RefreshGamepadFocus(); + } + else + { + RefreshGamepadFocus(); + } + return true; + } + if (Key == EKeys::Gamepad_DPad_Right) + { + CancelPendingPress(); + if (FocusedItemIndex == -2) + { + RefreshGamepadFocus(false); + } + else if (FocusedItemIndex == -1) + { + SelectTabByIndex(ActiveTabIndex + 1); + } + else if (ActiveItems.Num() > 1) + { + FocusedItemIndex = (FocusedItemIndex + 1) % ActiveItems.Num(); + RefreshGamepadFocus(); + } + else + { + RefreshGamepadFocus(); + } + return true; + } + if (Key == EKeys::Gamepad_DPad_Up) + { + CancelPendingPress(); + if (FocusedItemIndex >= 0) + { + FocusedItemIndex = -1; + RefreshGamepadFocus(false); + } + else if (FocusedItemIndex == -1) + { + UScrollBox* TargetScroll = GetActiveReadOnlyScrollBox(); + if (TargetScroll && TargetScroll->GetScrollOffset() > KINDA_SMALL_NUMBER) + { + const float MaxOffset = FMath::Max(0.0f, TargetScroll->GetScrollOffsetOfEnd()); + TargetScroll->SetScrollOffset(FMath::Clamp(TargetScroll->GetScrollOffset() - 60.0f, 0.0f, MaxOffset)); + } + else if (BackButton) + { + FocusedItemIndex = -2; + RefreshGamepadFocus(false); + } + } + return true; + } + if (Key == EKeys::Gamepad_DPad_Down) + { + CancelPendingPress(); + if (FocusedItemIndex == -2) + { + FocusedItemIndex = -1; + RefreshGamepadFocus(false); + } + else if (FocusedItemIndex == -1) + { + if (ActiveItems.Num() > 0) + { + FocusedItemIndex = GetDefaultItemIndexForTab(ActiveTabIndex, ActiveItems); + RefreshGamepadFocus(true); + } + else if (UScrollBox* TargetScroll = GetActiveReadOnlyScrollBox()) + { + const float MaxOffset = FMath::Max(0.0f, TargetScroll->GetScrollOffsetOfEnd()); + TargetScroll->SetScrollOffset(FMath::Clamp(TargetScroll->GetScrollOffset() + 60.0f, 0.0f, MaxOffset)); + } + } + return true; + } + if (Key == EKeys::Gamepad_FaceButton_Bottom) + { + if (FocusedItemIndex == -2 && BackButton) + { + bBackButtonPressed = true; + RefreshGamepadFocus(false); + } + else if (FocusedItemIndex >= 0 && FocusedItemIndex < ActiveItems.Num()) + { + GamepadPressedItem = ActiveItems[FocusedItemIndex]; + GamepadPressedItem->SetButtonPressed(true); + } + else if (FocusedItemIndex == -1 && ActiveItems.Num() > 0) + { + GamepadPressedItem.Reset(); + FocusedItemIndex = GetDefaultItemIndexForTab(ActiveTabIndex, ActiveItems); + RefreshGamepadFocus(true); + } + return true; + } + + return false; +} diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Actors/TrivialKartHUD.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Actors/TrivialKartHUD.h index b61d43a0..6ff9ef1c 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Actors/TrivialKartHUD.h +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Actors/TrivialKartHUD.h @@ -23,6 +23,7 @@ #include "TrivialKartHUD.generated.h" class UTexture2D; +class UTrivialKartTabbedModalWidget; DECLARE_LOG_CATEGORY_EXTERN(LogTemplateHUD, Log, All); @@ -64,6 +65,7 @@ class TRIVIALKART_UNREAL_API ATrivialKartHUD : public AHUD UUserWidget* GetWidgetOfType(const EWidgetType WidgetType); bool HandleGamepadKey(const FKey& Key, bool bIsPressed = true, bool bIsRepeat = false); + bool IsLoadingOpen() const; bool IsSubMenuOpen() const; bool IsUIBlockingInput() const; bool IsStickNavigationEnabled() const; @@ -78,6 +80,7 @@ class TRIVIALKART_UNREAL_API ATrivialKartHUD : public AHUD private: static bool IsSubMenuWidgetType(EWidgetType WidgetType); + UTrivialKartTabbedModalWidget* GetActiveSubMenuWidget() const; template T* GetActiveWidget(const EWidgetType WidgetType) const diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Controllers/TrivialKartGamepadInputProcessor.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Controllers/TrivialKartGamepadInputProcessor.h index 5074e991..17d31842 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Controllers/TrivialKartGamepadInputProcessor.h +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Controllers/TrivialKartGamepadInputProcessor.h @@ -17,6 +17,7 @@ #include "CoreMinimal.h" #include "Framework/Application/IInputProcessor.h" +#include "GenericPlatform/GenericPlatformInputDeviceMapper.h" #include "InputCoreTypes.h" #include "UObject/WeakObjectPtr.h" @@ -31,6 +32,14 @@ enum class ETrivialKartStickDir : uint8 Right }; +enum class ETrivialKartDeviceTriggerSignature : uint8 +{ + Unknown, + PlayStationHalfRest, + AnalogTriggerCapable, + SwitchDigitalOnly +}; + class TRIVIALKART_UNREAL_API FTrivialKartGamepadInputProcessor : public IInputProcessor { public: @@ -46,11 +55,55 @@ class TRIVIALKART_UNREAL_API FTrivialKartGamepadInputProcessor : public IInputPr virtual bool HandleMouseMoveEvent(FSlateApplication& SlateApp, const FPointerEvent& MouseEvent) override; void ResetState(); + void ResetDeviceCapabilities(); + void RemoveDeviceState(FInputDeviceId DeviceId); + float GetMaxTriggerAnalog(bool bRightTrigger) const; + bool IsDigitalTriggerHeld(bool bRightTrigger) const; + ETrivialKartDeviceTriggerSignature GetDeviceTriggerSignature(FInputDeviceId DeviceId) const; + bool IsPrimaryTouchHeld() const { return bIsPrimaryTouchHeld; } + bool IsPrimaryMouseHeld() const { return bIsPrimaryMouseHeld; } + void ClearPrimaryTouchHeld() { bIsPrimaryTouchHeld = false; } + void ClearPointerDriveHeld() + { + bIsPrimaryTouchHeld = false; + bIsPrimaryMouseHeld = false; + } void ResetAnalogState(); void LatchStickUntilNeutral(); private: + struct FTrivialKartDeviceKey + { + FInputDeviceId DeviceId = INPUTDEVICEID_NONE; + FKey Key; + + bool operator==(const FTrivialKartDeviceKey& Other) const + { + return DeviceId == Other.DeviceId && Key == Other.Key; + } + + friend uint32 GetTypeHash(const FTrivialKartDeviceKey& Entry) + { + return HashCombine(GetTypeHash(Entry.DeviceId.GetId()), GetTypeHash(Entry.Key)); + } + }; + + struct FTrivialKartDeviceInputState + { + float LeftX = 0.0f; + float LeftY = 0.0f; + float LeftTriggerAnalog = 0.0f; + float RightTriggerAnalog = 0.0f; + bool bHasLeftTriggerAnalog = false; + bool bHasRightTriggerAnalog = false; + bool bSawSubHalfTrigger = false; + bool bDigitalLeftTriggerHeld = false; + bool bDigitalRightTriggerHeld = false; + ETrivialKartDeviceTriggerSignature TriggerSignature = ETrivialKartDeviceTriggerSignature::Unknown; + }; + bool ProcessKeyEvent(const FKeyEvent& InKeyEvent, bool bIsPressed); + void GetDominantStickAxes(float& OutLeftX, float& OutLeftY) const; ETrivialKartStickDir ComputeDesiredStickDir() const; static FKey StickDirToKey(ETrivialKartStickDir Dir); void OnApplicationActivationChanged(const bool bIsActive); @@ -58,16 +111,15 @@ class TRIVIALKART_UNREAL_API FTrivialKartGamepadInputProcessor : public IInputPr TWeakObjectPtr OwnerController; FDelegateHandle AppActivationHandle; - TSet ConsumedPressedKeys; - TSet HeldPhysicalKeys; - TSet LatchedRepeatKeys; + TSet ConsumedPressedKeys; + TSet HeldPhysicalKeys; + TSet LatchedRepeatKeys; + TMap DeviceStates; FVector2D AccumulatedMouseDelta = FVector2D::ZeroVector; double LastGamepadActivityTimeSeconds = -100.0; - float CachedLeftX = 0.0f; - float CachedLeftY = 0.0f; - float CachedLeftTrigger = 0.0f; - float CachedRightTrigger = 0.0f; + bool bIsPrimaryTouchHeld = false; + bool bIsPrimaryMouseHeld = false; ETrivialKartStickDir ActiveStickDir = ETrivialKartStickDir::None; float StickRepeatRemaining = 0.0f; bool bLatchUntilNeutral = false; diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Controllers/TrivialKartPlayerController.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Controllers/TrivialKartPlayerController.h index 0eafaab5..7f9ab7d0 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Controllers/TrivialKartPlayerController.h +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Controllers/TrivialKartPlayerController.h @@ -18,6 +18,7 @@ #include "Containers/Ticker.h" #include "CoreMinimal.h" #include "GameFramework/PlayerController.h" +#include "GenericPlatform/GenericPlatformInputDeviceMapper.h" #include "InputCoreTypes.h" #include "InputModifiers.h" #include "TrivialKartPlayerController.generated.h" @@ -33,18 +34,45 @@ enum class ETrivialKartInputMode : uint8 Gamepad }; +enum class ETrivialKartGamepadStyle : uint8 +{ + GenericXbox, + PlayStation, + NintendoSwitch +}; + +UENUM() +enum class ETrivialKartDriveGateRule : uint8 +{ + StandardKey, + AnalogTriggerAxis, + DigitalTriggerKey, + TouchHold, + MouseHold +}; + DECLARE_MULTICAST_DELEGATE_OneParam(FInputModeUpdated, ETrivialKartInputMode); /** - * Clamps trigger axis input so negative HID resting values (-1.0f) and - * uncalibrated Android DualSense resting values (+0.50f) do not actuate driving. + * Unified input modifier for runtime gameplay driving mappings: + * - Gates driving while UI overlays or bottom-bar menu focus block gameplay (without dynamic + * RemoveMappingContext/AddMappingContext rebuilds that lock out DualSense +0.50f resting triggers). + * - Evaluates per-device analog trigger axes (>= 0.65f) and digital-only triggers independently so + * simultaneously connected controllers never overwrite or suppress each other's inputs. + * - Guards Touch1 and LeftMouseButton against DualSense touchpad phantom touches and UI clicks. */ UCLASS() -class TRIVIALKART_UNREAL_API UTrivialKartPositiveTriggerModifier : public UInputModifier +class TRIVIALKART_UNREAL_API UTrivialKartDriveInputModifier : public UInputModifier { GENERATED_BODY() public: + UPROPERTY(EditAnywhere, Category = "Settings") + ETrivialKartDriveGateRule GateRule = ETrivialKartDriveGateRule::StandardKey; + + UPROPERTY(EditAnywhere, Category = "Settings") + FKey TargetKey; + UPROPERTY(EditAnywhere, Category = "Settings") float ActiveThreshold = 0.65f; @@ -56,41 +84,65 @@ class TRIVIALKART_UNREAL_API UTrivialKartPositiveTriggerModifier : public UInput }; /** - * + * PlayerController managing unified Touch, Keyboard/Mouse, and multi-Gamepad input routing. */ UCLASS() class TRIVIALKART_UNREAL_API ATrivialKartPlayerController : public APlayerController { GENERATED_BODY() - - UPROPERTY(EditAnywhere, Category ="Input|Input Mappings") - TObjectPtr DefaultMappingContext; - UPROPERTY(EditAnywhere, Category ="Input|Input Mappings") - TObjectPtr UIMappingContext; + UPROPERTY(EditAnywhere, Category = "Input|Input Mappings") + TObjectPtr DefaultMappingContext; UPROPERTY(Transient) TObjectPtr RuntimeGameplayMappingContext; + struct FTrivialKartAndroidGamepadInfo + { + int32 AndroidDeviceId = -1; + int32 ControllerNumber = 0; + int32 VendorId = 0; + FString DeviceName; + ETrivialKartGamepadStyle Style = ETrivialKartGamepadStyle::GenericXbox; + }; + + struct FTrivialKartUnrealSlotBinding + { + int32 SlotIndex = INDEX_NONE; + FString SlotName; + bool bEvaluated = false; + }; + TSharedPtr GamepadInputProcessor; FDelegateHandle DeviceConnectionChangeHandle; FTSTicker::FDelegateHandle DeviceCheckTickerHandle; FTSTicker::FDelegateHandle PeriodicDevicePollHandle; + TArray CachedAndroidGamepads; + TMap KnownAndroidDeviceStyles; + TArray PendingHotplugStyles; + TSet SeenUnrealGamepadDevices; + TMap ConfirmedUnrealDeviceStyles; + TMap UnrealDeviceSlotBindings; + TSet ClaimedAndroidControllerSlots; + FInputDeviceId LastActiveGamepadDeviceId = INPUTDEVICEID_NONE; + bool bHasInitialAndroidSnapshot = false; + #if PLATFORM_ANDROID ETrivialKartInputMode ActiveInputMode = ETrivialKartInputMode::Touch; #else ETrivialKartInputMode ActiveInputMode = ETrivialKartInputMode::KeyboardMouse; #endif ETrivialKartInputMode PreviousNonGamepadMode = ActiveInputMode; + ETrivialKartGamepadStyle ActiveGamepadStyle = ETrivialKartGamepadStyle::GenericXbox; bool bGameplayInputEnabled = true; bool bKeyNavigationActive = false; bool bWasGamepadAttached = false; double LastNonGamepadInputTimeSeconds = -100.0; - + public: ATrivialKartPlayerController(); - + virtual void BeginPlay() override; virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; virtual void SetupInputComponent() override; @@ -98,16 +150,23 @@ class TRIVIALKART_UNREAL_API ATrivialKartPlayerController : public APlayerContro bool HandleGamepadKey(const FKey& InKey, bool bIsPressed = true, bool bIsRepeat = false, bool bIsShiftDown = false); bool HandleUICancelKey(bool bIsPressed); + bool IsLoadingOpen() const; bool IsSubMenuOpen() const; bool IsUIBlockingInput() const; + bool IsGameplayDrivingAllowed() const; bool IsStickNavigationEnabled() const; + bool IsPointOverPlayBoardMenuButton(const FVector2D& ScreenSpacePosition) const; bool IsGamepadAttached() const { return bWasGamepadAttached; } void SetGameplayInputEnabled(bool bEnabled); void SetActiveInputMode(ETrivialKartInputMode NewMode); ETrivialKartInputMode GetActiveInputMode() const { return ActiveInputMode; } + ETrivialKartGamepadStyle GetActiveGamepadStyle() const { return ActiveGamepadStyle; } void NotifyExplicitDeviceInput(ETrivialKartInputMode DetectedMode); + void NotifyExplicitGamepadInput(FInputDeviceId SourceDeviceId); + void NotifyGamepadDeviceDiscovered(FInputDeviceId SourceDeviceId); + void NotifyGamepadHardwareSignatureUpdated(FInputDeviceId SourceDeviceId); void NotifyPointerDeviceInput(ETrivialKartInputMode PointerMode); void SetKeyNavigationActive(bool bActive); bool IsKeyNavigationActive() const { return ActiveInputMode == ETrivialKartInputMode::Gamepad || bKeyNavigationActive; } @@ -116,6 +175,10 @@ class TRIVIALKART_UNREAL_API ATrivialKartPlayerController : public APlayerContro void NotifyViewportPointerDown(const FVector2D& ScreenSpacePosition); void CancelPendingPresses(); void LatchStickUntilNeutral(); + float GetTriggerAnalogValue(const FKey& TriggerAxisKey) const; + bool IsDigitalTriggerHeld(const FKey& DigitalTriggerKey) const; + bool IsPrimaryTouchHeld() const; + bool IsPrimaryMouseHeld() const; void RestoreFocusToGameViewport(); int32 GetLocalPlayerUserIndex() const; @@ -127,10 +190,20 @@ class TRIVIALKART_UNREAL_API ATrivialKartPlayerController : public APlayerContro private: UInputMappingContext* GetOrCreateGameplayMappingContext(); - static FKey ResolveCanonicalUIKey(const UInputAction* Action, const TArray& UIMappings); static FKey ResolveFallbackUIKey(const FKey& InKey, bool bIsShiftDown); static bool IsDirectionalUIKey(const FKey& Key); - static bool QueryAnyGamepadAttached(); + static bool IsDirectGameplayDriveKey(const FKey& Key); + bool QueryAnyGamepadAttached() const; + void RefreshAndroidGamepadSnapshot(); + void InvalidatePendingUnrealSlotEvaluations(); + void EvictUnrealGamepadDevice(FInputDeviceId DeviceId); + int32 CountConnectedAndroidStyle(ETrivialKartGamepadStyle Style) const; + bool HasConnectedAndroidStyle(ETrivialKartGamepadStyle Style) const { return CountConnectedAndroidStyle(Style) > 0; } + bool TryPopUniformPendingHotplugStyle(ETrivialKartGamepadStyle& OutStyle); + bool TryClassifyGamepadName(const FString& ControllerName, ETrivialKartGamepadStyle& OutStyle) const; + bool TryResolveStyleFromUnrealControllerSlot(FInputDeviceId SourceDeviceId, ETrivialKartGamepadStyle& OutStyle); + ETrivialKartGamepadStyle ResolveGamepadStyleForDevice(FInputDeviceId SourceDeviceId); + void RefreshGamepadStyleForDevice(FInputDeviceId SourceDeviceId, bool bBroadcastIfChanged); void RemapAllDevicesToPrimaryUser() const; void SyncGamepadAttachmentState(); void OnInputDeviceConnectionChange(EInputDeviceConnectionState NewConnectionState, FPlatformUserId PlatformUserId, FInputDeviceId InputDeviceId); diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/GameInstances/TrivialKartGameInstance.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/GameInstances/TrivialKartGameInstance.h index 943f5ab5..41921f36 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/GameInstances/TrivialKartGameInstance.h +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/GameInstances/TrivialKartGameInstance.h @@ -17,6 +17,7 @@ #pragma once +#include "Containers/Ticker.h" #include "CoreMinimal.h" #include "Interfaces/OnlineExternalUIInterface.h" #include "Interfaces/OnlineStoreInterfaceV2.h" @@ -57,6 +58,7 @@ class TRIVIALKART_UNREAL_API UTrivialKartGameInstance : public UPlatformGameInst void CheckPendingPurchases(); UTrivialKartSaveGame* LoadGame(); void SaveGame(UTrivialKartSaveGame* SaveData); + bool IsCloudSyncInFlight() const { return bCloudSyncInFlight; } protected: UPROPERTY(EditAnywhere) @@ -88,5 +90,12 @@ class TRIVIALKART_UNREAL_API UTrivialKartGameInstance : public UPlatformGameInst void OnCloudReadComplete(bool bWasSuccessful, const FUniqueNetId& UserId, const FString& FileName); void OnCloudWriteComplete(bool bWasSuccessful, const FUniqueNetId& UserId, const FString& FileName); + + void ArmCloudSyncWatchdog(); + void ClearCloudSyncWatchdog(); + void DismissLoadingScreen(); + + FTSTicker::FDelegateHandle CloudSyncTimeoutHandle; + bool bCloudSyncInFlight = false; }; diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Infos/TrivialKartPlayerState.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Infos/TrivialKartPlayerState.h index b4573c2b..c5805a6a 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Infos/TrivialKartPlayerState.h +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Infos/TrivialKartPlayerState.h @@ -66,6 +66,7 @@ class TRIVIALKART_UNREAL_API ATrivialKartPlayerState : public APlayerState void AddDistance(const float DistanceTravelled); void ConsumeCoins(const int CoinsUsed); void AddCarToInventory(const FString& CarID); + bool PurchaseCarWithCoins(const FString& CarID, const int CoinsUsed); float GetFuel() const; float GetDistance() const; diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/GarageWidget.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/GarageWidget.h index 1c19328d..475ab614 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/GarageWidget.h +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/GarageWidget.h @@ -17,83 +17,37 @@ #pragma once #include "CoreMinimal.h" -#include "Blueprint/UserWidget.h" -#include "Controllers/TrivialKartPlayerController.h" -#include "InputCoreTypes.h" -#include "Styling/SlateTypes.h" +#include "Widgets/TrivialKartTabbedModalWidget.h" #include "GarageWidget.generated.h" -class UBorder; -class UButton; -class UWidgetSwitcher; class UCheckBox; class USelectableItem; /** - * + * Garage modal widget managing Kart and Level selection tabs. */ UCLASS() -class TRIVIALKART_UNREAL_API UGarageWidget : public UUserWidget +class TRIVIALKART_UNREAL_API UGarageWidget : public UTrivialKartTabbedModalWidget { GENERATED_BODY() - - UPROPERTY(meta=(BindWidget)) - TObjectPtr BackButton; - + UPROPERTY(meta=(BindWidget)) TObjectPtr KartCheckBox; - + UPROPERTY(meta=(BindWidget)) TObjectPtr LevelCheckBox; - - UPROPERTY(meta=(BindWidget)) - TObjectPtr ContentSwitcher; - -protected: - UPROPERTY() - TArray CheckBoxes; - - UPROPERTY(Transient) - TArray> TabHighlightBorders; - - TWeakObjectPtr GamepadPressedItem; - TWeakObjectPtr HoveredItem; - int32 ActiveTabIndex = 0; - int32 FocusedItemIndex = 0; - FButtonStyle OriginalBackButtonStyle; - FLinearColor OriginalBackButtonBgColor = FLinearColor::White; - bool bBackStyleCached = false; - bool bBackButtonPressed = false; - -public: - virtual void NativeConstruct() override; - virtual void NativeDestruct() override; +protected: + virtual EWidgetType GetModalWidgetType() const override { return EWidgetType::Garage; } + virtual void RegisterTabCheckBoxes(TArray& OutCheckBoxes) override; + virtual void BindTabCheckBoxEvents() override; + virtual void UnbindTabCheckBoxEvents() override; + virtual int32 GetDefaultItemIndexForTab(int32 TabIndex, const TArray& ActiveItems) const override; - bool HandleGamepadKey(const FKey& Key, bool bIsPressed = true); - void RefreshGamepadFocus(bool bScrollIntoView = true); - void RefreshOwnershipAndFocus(bool bScrollIntoView = false); - void CancelPendingPress(); - private: - UFUNCTION() - void OnBackButtonClicked(); - UFUNCTION() - void OnBackButtonReleased(); - void SetCheckBoxState(bool bIsChecked, UCheckBox* CheckBox, int ActiveWidgetIndex); - void SelectTabByIndex(int32 NewTabIndex); - void RefreshAllItemsOwnership() const; - void GatherSelectableItems(UWidget* RootWidget, TArray& OutItems, bool bOnlySelectable) const; - int32 FindActiveCarItemIndex() const; - void OnSelectableItemInteracted(USelectableItem* InteractedItem); - void OnSelectableItemUnhovered(USelectableItem* UnhoveredItem); - void OnSelectableItemClicked(USelectableItem* ClickedItem); - void OnInputModeChanged(ETrivialKartInputMode NewInputMode); - bool IsNavigationVisualActive() const; - void RestoreViewportFocus() const; - UFUNCTION() void OnKartBoxStateChanged(bool bIsChecked); + UFUNCTION() void OnLevelBoxStateChange(bool bIsChecked); }; diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/PGSWidget.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/PGSWidget.h index eef75e68..e7be9408 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/PGSWidget.h +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/PGSWidget.h @@ -17,91 +17,58 @@ #pragma once #include "CoreMinimal.h" -#include "Blueprint/UserWidget.h" -#include "Controllers/TrivialKartPlayerController.h" -#include "InputCoreTypes.h" -#include "Styling/SlateTypes.h" +#include "Widgets/TrivialKartTabbedModalWidget.h" #include "PGSWidget.generated.h" -class UBorder; +class UCheckBox; class UPGSLayoutText; class UScrollBox; class UVerticalBox; -class UWidgetSwitcher; -class UCheckBox; -class UButton; + /** - * + * Play Games Services modal widget managing Authentication, Achievements, and Leaderboard tabs. */ UCLASS() -class TRIVIALKART_UNREAL_API UPGSWidget : public UUserWidget +class TRIVIALKART_UNREAL_API UPGSWidget : public UTrivialKartTabbedModalWidget { GENERATED_BODY() - - UPROPERTY(meta=(BindWidget)) - TObjectPtr BackButton; - + UPROPERTY(meta=(BindWidget)) TObjectPtr AuthenticationCheckBox; - + UPROPERTY(meta=(BindWidget)) TObjectPtr AchievementsCheckBox; - + UPROPERTY(meta=(BindWidget)) TObjectPtr LeaderboardCheckBox; - - UPROPERTY(meta=(BindWidget)) - TObjectPtr ContentSwitcher; - + UPROPERTY(meta=(BindWidget)) TObjectPtr AuthBox; - + UPROPERTY(meta=(BindWidget)) TObjectPtr AchievementsBox; - + UPROPERTY(meta=(BindWidget)) TObjectPtr LeaderboardBox; - + UPROPERTY(EditAnywhere) TSubclassOf PGSTextTemplate; - -protected: - UPROPERTY() - TArray CheckBoxes; - - UPROPERTY(Transient) - TArray> TabHighlightBorders; - int32 ActiveTabIndex = 0; - bool bBackButtonFocused = false; - bool bBackButtonPressed = false; - FButtonStyle OriginalBackButtonStyle; - FLinearColor OriginalBackButtonBgColor = FLinearColor::White; - bool bBackStyleCached = false; - -public: - virtual void NativeConstruct() override; - virtual void NativeDestruct() override; +protected: + virtual EWidgetType GetModalWidgetType() const override { return EWidgetType::PGS; } + virtual void RegisterTabCheckBoxes(TArray& OutCheckBoxes) override; + virtual void BindTabCheckBoxEvents() override; + virtual void UnbindTabCheckBoxEvents() override; + virtual void InitializeModalContent() override; + virtual UScrollBox* GetActiveReadOnlyScrollBox() const override; - bool HandleGamepadKey(const FKey& Key, bool bIsPressed = true); - void CancelPendingPress(); - private: - UFUNCTION() - void OnBackButtonClicked(); - UFUNCTION() - void OnBackButtonReleased(); - void SetCheckBoxState(bool bIsChecked, UCheckBox* CheckBox, int ActiveWidgetIndex); - void SelectTabByIndex(int32 NewTabIndex); - void UpdateTabFocusVisuals(); - void OnInputModeChanged(ETrivialKartInputMode NewInputMode); - bool IsNavigationVisualActive() const; - void RestoreViewportFocus() const; - UFUNCTION() void OnAuthCheckBoxStateChanged(bool bIsChecked); + UFUNCTION() void OnAchievementBoxStateChange(bool bIsChecked); + UFUNCTION() void OnLeaderboardBoxStateChange(bool bIsChecked); }; diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/PlayBoardWidget.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/PlayBoardWidget.h index 26986c03..fa2fc010 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/PlayBoardWidget.h +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/PlayBoardWidget.h @@ -21,7 +21,6 @@ #include "Controllers/TrivialKartPlayerController.h" #include "InputCoreTypes.h" #include "Misc/Optional.h" -#include "Styling/SlateTypes.h" #include "PlayBoardWidget.generated.h" class UBorder; @@ -56,18 +55,16 @@ class TRIVIALKART_UNREAL_API UPlayBoardWidget : public UUserWidget UPROPERTY(meta=(BindWidget)) TObjectPtr FuelBar; - TWeakObjectPtr InputGuideBorder; TWeakObjectPtr InputGuideText; TWeakObjectPtr TouchDrivePadSizeBox; TWeakObjectPtr TouchDrivePadBorder; + TWeakObjectPtr MenuButtonHighlightBorders[3]; int32 FocusedButtonIndex = -1; int32 PressedButtonIndex = -1; bool bFocusedByHover = false; TOptional LastRenderedGuideMode; - FButtonStyle OriginalButtonStyles[3]; - FLinearColor OriginalBackgroundColors[3]; - bool bStylesCached = false; + TOptional LastRenderedGamepadStyle; public: virtual TSharedRef RebuildWidget() override; @@ -75,8 +72,8 @@ class TRIVIALKART_UNREAL_API UPlayBoardWidget : public UUserWidget virtual void NativeDestruct() override; bool HandleGamepadKey(const FKey& Key, bool bIsPressed = true, bool bIsRepeat = false); - bool HasMenuFocus() const { return FocusedButtonIndex >= 0; } bool HasBlockingMenuFocus() const { return FocusedButtonIndex >= 0 && !bFocusedByHover; } + bool IsPointOverAnyMenuButton(const FVector2D& ScreenSpacePosition) const; void ClearMenuFocus(bool bOnlyIfNotHovered = false); void CancelPendingPress(); void OnViewportPointerDown(const FVector2D& ScreenSpacePosition); @@ -84,8 +81,8 @@ class TRIVIALKART_UNREAL_API UPlayBoardWidget : public UUserWidget private: void EnsureInputGuideWidget(); + void EnsureMenuButtonHighlightFrames(); bool IsAnyMenuButtonHovered() const; - bool IsPointOverAnyMenuButton(const FVector2D& ScreenSpacePosition) const; void SetHoverFocus(int32 NewButtonIndex); void SetKeyboardOrGamepadFocus(int32 NewButtonIndex); diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/SelectableItem.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/SelectableItem.h index a82387d0..73def015 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/SelectableItem.h +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/SelectableItem.h @@ -39,10 +39,8 @@ enum class EPurchaseObject : uint8 Coin, Subscription }; -class UButtonWidgetStyle; class UButton; class UBorder; -class SButton; /** * */ diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/StoreWidget.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/StoreWidget.h index a88f79fc..f527c9ab 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/StoreWidget.h +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/StoreWidget.h @@ -17,92 +17,47 @@ #pragma once #include "CoreMinimal.h" -#include "Blueprint/UserWidget.h" -#include "Controllers/TrivialKartPlayerController.h" -#include "InputCoreTypes.h" -#include "Styling/SlateTypes.h" +#include "Widgets/TrivialKartTabbedModalWidget.h" #include "StoreWidget.generated.h" -class UBorder; -class UButton; -class UWidgetSwitcher; class UCheckBox; -class USelectableItem; /** - * + * Store modal widget managing Fuel, Coin, Car, and Subscription tabs. */ UCLASS() -class TRIVIALKART_UNREAL_API UStoreWidget : public UUserWidget +class TRIVIALKART_UNREAL_API UStoreWidget : public UTrivialKartTabbedModalWidget { GENERATED_BODY() - - UPROPERTY(meta=(BindWidget)) - TObjectPtr BackButton; - + UPROPERTY(meta=(BindWidget)) TObjectPtr FuelCheckBox; - + UPROPERTY(meta=(BindWidget)) TObjectPtr CoinCheckBox; - + UPROPERTY(meta=(BindWidget)) TObjectPtr CarCheckBox; - + UPROPERTY(meta=(BindWidget)) TObjectPtr SubscriptionCheckBox; - - UPROPERTY(meta=(BindWidget)) - TObjectPtr ContentSwitcher; - -protected: - UPROPERTY() - TArray CheckBoxes; - - UPROPERTY(Transient) - TArray> TabHighlightBorders; - - TWeakObjectPtr GamepadPressedItem; - TWeakObjectPtr HoveredItem; - int32 ActiveTabIndex = 0; - int32 FocusedItemIndex = 0; - FButtonStyle OriginalBackButtonStyle; - FLinearColor OriginalBackButtonBgColor = FLinearColor::White; - bool bBackStyleCached = false; - bool bBackButtonPressed = false; - -public: - virtual void NativeConstruct() override; - virtual void NativeDestruct() override; +protected: + virtual EWidgetType GetModalWidgetType() const override { return EWidgetType::Store; } + virtual void RegisterTabCheckBoxes(TArray& OutCheckBoxes) override; + virtual void BindTabCheckBoxEvents() override; + virtual void UnbindTabCheckBoxEvents() override; - bool HandleGamepadKey(const FKey& Key, bool bIsPressed = true); - void RefreshGamepadFocus(bool bScrollIntoView = true); - void RefreshOwnershipAndFocus(bool bScrollIntoView = false); - void CancelPendingPress(); - private: - UFUNCTION() - void OnBackButtonClicked(); - UFUNCTION() - void OnBackButtonReleased(); - void SetCheckBoxState(bool bIsChecked, UCheckBox* CheckBox, int ActiveWidgetIndex); - void SelectTabByIndex(int32 NewTabIndex); - void RefreshAllItemsOwnership() const; - void GatherSelectableItems(UWidget* RootWidget, TArray& OutItems, bool bOnlySelectable) const; - void OnSelectableItemInteracted(USelectableItem* InteractedItem); - void OnSelectableItemUnhovered(USelectableItem* UnhoveredItem); - void OnSelectableItemClicked(USelectableItem* ClickedItem); - void OnInputModeChanged(ETrivialKartInputMode NewInputMode); - bool IsNavigationVisualActive() const; - void RestoreViewportFocus() const; - UFUNCTION() void OnFuelBoxStateChanged(bool bIsChecked); + UFUNCTION() void OnCoinBoxStateChange(bool bIsChecked); + UFUNCTION() void OnCarBoxStateChange(bool bIsChecked); + UFUNCTION() void OnSubscriptionBoxStateChange(bool bIsChecked); }; diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/TrivialKartTabbedModalWidget.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/TrivialKartTabbedModalWidget.h new file mode 100644 index 00000000..d1d73904 --- /dev/null +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/TrivialKartTabbedModalWidget.h @@ -0,0 +1,109 @@ +/* +* Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "CoreMinimal.h" +#include "Actors/TrivialKartHUD.h" +#include "Blueprint/UserWidget.h" +#include "Controllers/TrivialKartPlayerController.h" +#include "InputCoreTypes.h" +#include "Styling/SlateTypes.h" +#include "TrivialKartTabbedModalWidget.generated.h" + +class UBorder; +class UButton; +class UCheckBox; +class UScrollBox; +class USelectableItem; +class UWidget; +class UWidgetSwitcher; + +/** + * Shared base class for TrivialKart modal submenus (Store, Garage, PGS) providing + * unified controller, keyboard, mouse, and touch tab/item/close-button navigation. + */ +UCLASS(Abstract) +class TRIVIALKART_UNREAL_API UTrivialKartTabbedModalWidget : public UUserWidget +{ + GENERATED_BODY() + +protected: + UPROPERTY(meta=(BindWidget)) + TObjectPtr BackButton; + + UPROPERTY(meta=(BindWidget)) + TObjectPtr ContentSwitcher; + + UPROPERTY() + TArray CheckBoxes; + + UPROPERTY(Transient) + TArray> TabHighlightBorders; + + TArray>> CachedItemsByTab; + TArray> CachedAllItems; + TWeakObjectPtr GamepadPressedItem; + TWeakObjectPtr HoveredItem; + + int32 ActiveTabIndex = 0; + int32 FocusedItemIndex = -1; + FButtonStyle OriginalBackButtonStyle; + FLinearColor OriginalBackButtonBgColor = FLinearColor::White; + bool bBackStyleCached = false; + bool bBackButtonPressed = false; + +public: + virtual void NativeConstruct() override; + virtual void NativeDestruct() override; + + bool HandleGamepadKey(const FKey& Key, bool bIsPressed = true); + void RefreshGamepadFocus(bool bScrollIntoView = true); + void RefreshOwnershipAndFocus(bool bScrollIntoView = false); + void CancelPendingPress(); + +protected: + virtual EWidgetType GetModalWidgetType() const { return EWidgetType::None; } + virtual void RegisterTabCheckBoxes(TArray& OutCheckBoxes) {} + virtual void BindTabCheckBoxEvents() {} + virtual void UnbindTabCheckBoxEvents() {} + virtual void InitializeModalContent() {} + virtual int32 GetDefaultItemIndexForTab(int32 TabIndex, const TArray& ActiveItems) const { return 0; } + virtual UScrollBox* GetActiveReadOnlyScrollBox() const { return nullptr; } + + void SetCheckBoxState(bool bIsChecked, UCheckBox* CheckBox, int32 ActiveWidgetIndex); + void SelectTabByIndex(int32 NewTabIndex); + void GatherSelectableItems(UWidget* RootWidget, TArray& OutItems, bool bOnlySelectable) const; + void GetActiveSelectableItems(TArray& OutItems) const; + bool IsNavigationVisualActive() const; + void RestoreViewportFocus() const; + +private: + UFUNCTION() + void OnBackButtonClicked(); + + UFUNCTION() + void OnBackButtonReleased(); + + void ConfigureModalHitTesting(); + void CacheAndBindSelectableItems(); + void UnbindSelectableItems(); + void RefreshAllItemsOwnership() const; + void OnSelectableItemInteracted(USelectableItem* InteractedItem); + void OnSelectableItemUnhovered(USelectableItem* UnhoveredItem); + void OnSelectableItemClicked(USelectableItem* ClickedItem); + void OnInputModeChanged(ETrivialKartInputMode NewInputMode); +}; diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/TrivialKartUIStyle.h b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/TrivialKartUIStyle.h new file mode 100644 index 00000000..6f02d2b6 --- /dev/null +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/Public/Widgets/TrivialKartUIStyle.h @@ -0,0 +1,95 @@ +/* +* Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "CoreMinimal.h" +#include "Blueprint/WidgetTree.h" +#include "Components/HorizontalBox.h" +#include "Components/Image.h" +#include "Components/Overlay.h" +#include "Components/TextBlock.h" +#include "Components/VerticalBox.h" +#include "Styling/SlateBrush.h" +#include "Styling/SlateColor.h" + +namespace TrivialKartUIStyle +{ + inline void NormalizeWidgetTreeHitTesting(UWidgetTree* WidgetTree, const UWidget* ExcludedWidget = nullptr) + { + if (!WidgetTree) + { + return; + } + + WidgetTree->ForEachWidget([ExcludedWidget](UWidget* Widget) + { + if (!Widget || Widget == ExcludedWidget || Widget->GetVisibility() != ESlateVisibility::Visible) + { + return; + } + if (Cast(Widget) || Cast(Widget)) + { + Widget->SetVisibility(ESlateVisibility::HitTestInvisible); + } + else if (Cast(Widget) || Cast(Widget) || Cast(Widget)) + { + Widget->SetVisibility(ESlateVisibility::SelfHitTestInvisible); + } + }); + } + + inline FSlateBrush MakeRoundedHighlightBrush( + float CornerRadius, + float OutlineWidth, + const FLinearColor& TintColor, + const FLinearColor& OutlineColor, + const FVector2D& ImageSize = FVector2D::ZeroVector) + { + FSlateBrush Brush; + Brush.DrawAs = ESlateBrushDrawType::RoundedBox; + if (!ImageSize.IsZero()) + { + Brush.ImageSize = ImageSize; + } + Brush.TintColor = FSlateColor(TintColor); + Brush.OutlineSettings.CornerRadii = FVector4(CornerRadius, CornerRadius, CornerRadius, CornerRadius); + Brush.OutlineSettings.RoundingType = ESlateBrushRoundingType::FixedRadius; + Brush.OutlineSettings.Color = FSlateColor(OutlineColor); + Brush.OutlineSettings.Width = OutlineWidth; + return Brush; + } + + inline const FSlateBrush& GetEmptyBrush() + { + static const FSlateBrush EmptyBrush = []() + { + FSlateBrush Brush; + Brush.DrawAs = ESlateBrushDrawType::NoDrawType; + return Brush; + }(); + return EmptyBrush; + } + + inline FSlateBrush MakeButtonFocusBrush(bool bIsPressed, float CornerRadius = 12.0f) + { + return MakeRoundedHighlightBrush( + CornerRadius, + 6.0f, + bIsPressed ? FLinearColor(1.0f, 0.35f, 0.0f, 0.68f) : FLinearColor(1.0f, 0.45f, 0.0f, 0.48f), + FLinearColor(1.0f, 0.9f, 0.0f, 1.0f)); + } +} diff --git a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/TrivialKart_Unreal.Build.cs b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/TrivialKart_Unreal.Build.cs index e98cc3d3..c595a9c9 100644 --- a/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/TrivialKart_Unreal.Build.cs +++ b/trivialkart/trivialkart_unreal/Source/TrivialKart_Unreal/TrivialKart_Unreal.Build.cs @@ -45,6 +45,7 @@ public TrivialKart_Unreal(ReadOnlyTargetRules Target) : base(Target) if (Target.Platform == UnrealTargetPlatform.Android) { + PrivateDependencyModuleNames.Add("Launch"); DynamicallyLoadedModuleNames.Add("OnlineSubsystemGooglePlay"); string uplPath = Path.Combine(ModuleDirectory, "DEQP_UPL.xml"); AdditionalPropertiesForReceipt.Add("AndroidPlugin", uplPath);