UiGameLiftFlexMatchConnect.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <Components/UI/UiGameLiftFlexMatchConnect.h>
  9. #include <AzCore/Serialization/SerializeContext.h>
  10. #include <AzCore/Serialization/EditContext.h>
  11. #include <LyShine/Bus/UiButtonBus.h>
  12. #include <LyShine/Bus/UiCursorBus.h>
  13. #include <LyShine/Bus/UiElementBus.h>
  14. #include <LyShine/Bus/UiTextBus.h>
  15. namespace MPSGameLift
  16. {
  17. void UiGameLiftFlexMatchConnect::Reflect(AZ::ReflectContext* context)
  18. {
  19. if (const auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  20. {
  21. serializeContext->Class<UiGameLiftFlexMatchConnect, AZ::Component>()
  22. ->Version(1)
  23. ->Field("ConnectButton", &UiGameLiftFlexMatchConnect::m_connectButtonUi)
  24. ->Field("MatchmakingStatusTextUi", &UiGameLiftFlexMatchConnect::m_matchmakingStatusTextUi)
  25. ->Field("ExitButton", &UiGameLiftFlexMatchConnect::m_quitButtonUi)
  26. ->Field("AttemptConnectionBlockerUi", &UiGameLiftFlexMatchConnect::m_attemptConnectionBlockerUi)
  27. ->Field("ConnectToHostFailedUi", &UiGameLiftFlexMatchConnect::m_connectToHostFailedUi)
  28. ;
  29. if (AZ::EditContext* editContext = serializeContext->GetEditContext())
  30. {
  31. editContext->Class<UiGameLiftFlexMatchConnect>("UiGameLiftFlexMatchConnect", "Component to setup the start menu")
  32. ->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  33. ->Attribute(AZ::Edit::Attributes::Category, "Multiplayer Sample UI")
  34. ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/Component_Placeholder.svg")
  35. ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("CanvasUI"))
  36. ->DataElement(AZ::Edit::UIHandlers::Default, &UiGameLiftFlexMatchConnect::m_connectButtonUi, "Connect Button", "The UI button hosting a game (only available for unified launchers which can run as a client-host).")
  37. ->DataElement(AZ::Edit::UIHandlers::Default, &UiGameLiftFlexMatchConnect::m_matchmakingStatusTextUi, "Matchmaking Status Text", "The UI text to display the progress of finding a match after the player presses the connect button.")
  38. ->DataElement(AZ::Edit::UIHandlers::Default, &UiGameLiftFlexMatchConnect::m_quitButtonUi, "Quit Button", "The UI button to quit the app.")
  39. ->DataElement(AZ::Edit::UIHandlers::Default, &UiGameLiftFlexMatchConnect::m_attemptConnectionBlockerUi, "Attempt Connection Blocker", "Fullscreen UI for blocking user input while the client tries to connect.")
  40. ->DataElement(AZ::Edit::UIHandlers::Default, &UiGameLiftFlexMatchConnect::m_connectToHostFailedUi, "Connection To Host Failed", "UI to inform the user that connecting to the host failed.")
  41. ;
  42. }
  43. }
  44. }
  45. UiGameLiftFlexMatchConnect::UiGameLiftFlexMatchConnect()
  46. : m_onMatchmakingFailed{ [this](MatchmakingFailReason reason)
  47. {
  48. switch (reason)
  49. {
  50. case MatchmakingFailReason::FailedToReceiveTicket:
  51. PushStatusFail(StatusMatchmakingFailedToReceiveTicket);
  52. break;
  53. case MatchmakingFailReason::FailedToReceiveStatusUpdate:
  54. PushStatusFail(StatusMatchmakingFailedToReceiveStatusUpdate);
  55. break;
  56. case MatchmakingFailReason::TimedOut:
  57. PushStatusFail(StatusMatchmakingTimedOut);
  58. break;
  59. default:
  60. PushStatusFail(StatusMatchmakingFailedReasonUnknown);
  61. }
  62. } }
  63. {
  64. }
  65. void UiGameLiftFlexMatchConnect::Activate()
  66. {
  67. UiCursorBus::Broadcast(&UiCursorInterface::IncrementVisibleCounter);
  68. // Listen for button presses
  69. UiButtonBus::Event(m_quitButtonUi, &UiButtonInterface::SetOnClickCallback, [this]([[maybe_unused]] AZ::EntityId buttonEntityId, [[maybe_unused]] AZ::Vector2 position) { OnQuitClicked(); });
  70. UiButtonBus::Event(m_connectButtonUi, &UiButtonInterface::SetOnClickCallback, [this]([[maybe_unused]] AZ::EntityId buttonEntityId, [[maybe_unused]] AZ::Vector2 position) { OnConnectClicked(); });
  71. UiButtonBus::Event(m_connectToHostFailedUi, &UiButtonInterface::SetOnClickCallback, [this]([[maybe_unused]] AZ::EntityId buttonEntityId, [[maybe_unused]] AZ::Vector2 position) { OnConnectionFailedAcknowledged(); });
  72. // Hide the attempting connection ui until the player tries to connect
  73. UiElementBus::Event(m_attemptConnectionBlockerUi, &UiElementInterface::SetIsEnabled, false);
  74. // Listen for disconnect events to know if connecting to the host server failed
  75. AZ::Interface<Multiplayer::IMultiplayer>::Get()->AddEndpointDisconnectedHandler(m_onConnectToHostFailed);
  76. AZ::Interface<IRegionalLatencyFinder>::Get()->AddRequestLatenciesCompleteEventHandler(m_requestLatenciesComplete);
  77. // Listen for auth events
  78. AWSClientAuth::AWSCognitoAuthorizationNotificationBus::Handler::BusConnect();
  79. // Listen for matchmaking events
  80. AZ::Interface<IMatchmaking>::Get()->AddMatchmakingFailedEventHandler(m_onMatchmakingFailed);
  81. AZ::Interface<IMatchmaking>::Get()->AddMatchmakingSuccessEventHandler(m_onMatchmakingSuccess);
  82. AZ::Interface<IMatchmaking>::Get()->AddMatchmakingTicketReceivedEventHandler(m_onMatchmakingTicketReceived);
  83. }
  84. void UiGameLiftFlexMatchConnect::Deactivate()
  85. {
  86. AWSClientAuth::AWSCognitoAuthorizationNotificationBus::Handler::BusDisconnect();
  87. m_onConnectToHostFailed.Disconnect();
  88. UiCursorBus::Broadcast(&UiCursorInterface::DecrementVisibleCounter);
  89. }
  90. void UiGameLiftFlexMatchConnect::OnQuitClicked()
  91. {
  92. const auto console = AZ::Interface<AZ::IConsole>::Get();
  93. if (!console)
  94. {
  95. AZ_Assert(false, "UiGameLiftFlexMatchConnect attempting to use console commands before AZ::Console is available.");
  96. return;
  97. }
  98. console->PerformCommand("quit");
  99. }
  100. void UiGameLiftFlexMatchConnect::OnConnectClicked()
  101. {
  102. // Enable blocker ui while we attempt connection
  103. UiElementBus::Event(m_attemptConnectionBlockerUi, &UiElementInterface::SetIsEnabled, true);
  104. UiTextBus::Event(m_matchmakingStatusTextUi, &UiTextInterface::SetText, "Searching for match...");
  105. bool clientAuthInitialized = false;
  106. AWSClientAuth::AWSCognitoAuthorizationRequestBus::BroadcastResult(clientAuthInitialized, &AWSClientAuth::IAWSCognitoAuthorizationRequests::Initialize);
  107. if (clientAuthInitialized)
  108. {
  109. m_statusUpdates.push_back(StatusPlayerAuthInitSuccess);
  110. }
  111. else
  112. {
  113. PushStatusFail(StatusPlayerAuthInitFailed);
  114. return;
  115. }
  116. AWSClientAuth::AWSCognitoAuthorizationRequestBus::Broadcast(&AWSClientAuth::IAWSCognitoAuthorizationRequests::RequestAWSCredentialsAsync);
  117. }
  118. void UiGameLiftFlexMatchConnect::OnConnectionFailedAcknowledged()
  119. {
  120. // Player acknowledged connection failed. Close the warning popup.
  121. UiElementBus::Event(m_connectToHostFailedUi, &UiElementInterface::SetIsEnabled, false);
  122. UiElementBus::Event(m_attemptConnectionBlockerUi, &UiElementInterface::SetIsEnabled, false);
  123. m_statusUpdates.clear();
  124. }
  125. void UiGameLiftFlexMatchConnect::OnRequestLatenciesComplete(const RegionalLatencies& regionalLatencies)
  126. {
  127. if (regionalLatencies.empty())
  128. {
  129. PushStatusFail(StatusLatencyRequestFailed);
  130. return;
  131. }
  132. // Tell player server endpoints were reached and display the ping (estimate it as round-trip-time divided by 2)...
  133. AZStd::string latencyPrint;
  134. for (const auto& latency : regionalLatencies)
  135. {
  136. latencyPrint += AZStd::string::format("%s: %ims\n", latency.first.c_str(), static_cast<uint32_t>(latency.second.count()/2));
  137. }
  138. ReplaceStatusUpdate(AZStd::string::format(StatusLatencyRequestSuccess, latencyPrint.c_str()));
  139. // Start matchmaking
  140. AZ::Interface<IMatchmaking>::Get()->RequestMatch(regionalLatencies);
  141. }
  142. void UiGameLiftFlexMatchConnect::OnConnectToHostFailed()
  143. {
  144. UiElementBus::Event(m_attemptConnectionBlockerUi, &UiElementInterface::SetIsEnabled, false);
  145. UiElementBus::Event(m_connectToHostFailedUi, &UiElementInterface::SetIsEnabled, true);
  146. }
  147. void UiGameLiftFlexMatchConnect::OnRequestAWSCredentialsSuccess([[maybe_unused]] const AWSClientAuth::ClientAuthAWSCredentials& awsCredentials)
  148. {
  149. ReplaceStatusUpdate(StatusAnonPlayerCredentialsReceived);
  150. PushStatusUpdate(StatusRequestingServerRegionLatencies);
  151. AZ::Interface<IRegionalLatencyFinder>::Get()->RequestLatencies();
  152. }
  153. void UiGameLiftFlexMatchConnect::OnRequestAWSCredentialsFail([[maybe_unused]] const AZStd::string& error)
  154. {
  155. PushStatusFail(StatusAnonPlayerCredentialsFailed);
  156. }
  157. void UiGameLiftFlexMatchConnect::PushStatusUpdate(const AZStd::string& statusUpdate)
  158. {
  159. m_statusUpdates.push_back(statusUpdate);
  160. RenderStatusText();
  161. }
  162. void UiGameLiftFlexMatchConnect::ReplaceStatusUpdate(const AZStd::string& statusUpdate)
  163. {
  164. m_statusUpdates.pop_back();
  165. m_statusUpdates.push_back(statusUpdate);
  166. RenderStatusText();
  167. }
  168. void UiGameLiftFlexMatchConnect::PushStatusFail(const AZStd::string& reason)
  169. {
  170. // Display the latest status update in red
  171. const AZStd::string markupRedFont = "<font color = \"#ff0000\">";
  172. PushStatusUpdate(markupRedFont + reason + "</font>");
  173. // Enable the matchmaking failed popup, and allow the user to close the popup, and try again.
  174. UiElementBus::Event(m_connectToHostFailedUi, &UiElementInterface::SetIsEnabled, true);
  175. }
  176. void UiGameLiftFlexMatchConnect::RenderStatusText()
  177. {
  178. // Combine each all the status updates into a single list and render to UI text.
  179. AZStd::string statusTextbox;
  180. for (const auto& status : m_statusUpdates)
  181. {
  182. statusTextbox += status + "\n";
  183. }
  184. UiTextBus::Event(m_matchmakingStatusTextUi, &UiTextInterface::SetText, statusTextbox);
  185. }
  186. } // namespace MultiplayerSample