UiGameLiftConnectWithPlayerSessionData.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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/UiGameLiftConnectWithPlayerSessionData.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. #include <LyShine/Bus/UiTextInputBus.h>
  16. #include <LyShine/Bus/UiInteractableBus.h>
  17. #include <Multiplayer/Session/SessionRequests.h>
  18. #include <Request/AWSGameLiftSessionRequestBus.h>
  19. #include <AzCore/Jobs/JobContext.h>
  20. #include <AzCore/Jobs/JobFunction.h>
  21. #include <Multiplayer/Session/ISessionHandlingRequests.h>
  22. namespace MPSGameLift
  23. {
  24. void UiGameLiftConnectWithPlayerSessionData::Reflect(AZ::ReflectContext* context)
  25. {
  26. if (const auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  27. {
  28. serializeContext->Class<UiGameLiftConnectWithPlayerSessionData, AZ::Component>()
  29. ->Version(1)
  30. ->Field("ConnectButton", &UiGameLiftConnectWithPlayerSessionData::m_connectButtonUi)
  31. ->Field("ExitButton", &UiGameLiftConnectWithPlayerSessionData::m_quitButtonUi)
  32. ->Field("PlayerSessionDataInputUi", &UiGameLiftConnectWithPlayerSessionData::m_playerSessionDataJsonInputUi)
  33. ->Field("AttemptConnectionBlockerUi", &UiGameLiftConnectWithPlayerSessionData::m_attemptConnectionBlockerUi)
  34. ->Field("ConnectToHostFailedUi", &UiGameLiftConnectWithPlayerSessionData::m_connectToHostFailedUi)
  35. ->Field("JsonParseFailTextUi", &UiGameLiftConnectWithPlayerSessionData::m_jsonParseFailTextUi)
  36. ;
  37. if (AZ::EditContext* editContext = serializeContext->GetEditContext())
  38. {
  39. editContext->Class<UiGameLiftConnectWithPlayerSessionData>("UiGameLiftConnectWithPlayerSessionData", "Component to setup the start menu")
  40. ->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  41. ->Attribute(AZ::Edit::Attributes::Category, "Multiplayer Sample UI")
  42. ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/Component_Placeholder.svg")
  43. ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("CanvasUI"))
  44. ->DataElement(AZ::Edit::UIHandlers::Default, &UiGameLiftConnectWithPlayerSessionData::m_connectButtonUi, "Connect Button", "The UI button hosting a game (only available for unified launchers which can run as a client-host).")
  45. ->DataElement(AZ::Edit::UIHandlers::Default, &UiGameLiftConnectWithPlayerSessionData::m_quitButtonUi, "Quit Button", "The UI button to quit the app.")
  46. ->DataElement(AZ::Edit::UIHandlers::Default, &UiGameLiftConnectWithPlayerSessionData::m_playerSessionDataJsonInputUi, "GameLift Player Session Text Input", "The UI text input providing the game session and player session id.")
  47. ->DataElement(AZ::Edit::UIHandlers::Default, &UiGameLiftConnectWithPlayerSessionData::m_attemptConnectionBlockerUi, "Attempt Connection Blocker", "Fullscreen UI for blocking user input while the client tries to connect.")
  48. ->DataElement(AZ::Edit::UIHandlers::Default, &UiGameLiftConnectWithPlayerSessionData::m_connectToHostFailedUi, "Connection To Host Failed", "UI to inform the user that connecting to the host failed.")
  49. ->DataElement(AZ::Edit::UIHandlers::Default, &UiGameLiftConnectWithPlayerSessionData::m_jsonParseFailTextUi, "Json Parse Fail Text", "UI to inform the user that current JSON string is missing some expected data.")
  50. ;
  51. }
  52. }
  53. }
  54. void UiGameLiftConnectWithPlayerSessionData::Activate()
  55. {
  56. UiCursorBus::Broadcast(&UiCursorInterface::IncrementVisibleCounter);
  57. // Listen for button presses
  58. UiButtonBus::Event(m_quitButtonUi, &UiButtonInterface::SetOnClickCallback, [this](AZ::EntityId buttonEntityId, [[maybe_unused]] AZ::Vector2 position) { OnButtonClicked(buttonEntityId); });
  59. UiButtonBus::Event(m_connectButtonUi, &UiButtonInterface::SetOnClickCallback, [this](AZ::EntityId buttonEntityId, [[maybe_unused]] AZ::Vector2 position) { OnButtonClicked(buttonEntityId); });
  60. UiButtonBus::Event(m_connectToHostFailedUi, &UiButtonInterface::SetOnClickCallback, [this](AZ::EntityId buttonEntityId, [[maybe_unused]] AZ::Vector2 position) { OnButtonClicked(buttonEntityId); });
  61. UiTextInputBus::Event(m_playerSessionDataJsonInputUi, &UiTextInputInterface::SetOnChangeCallback, [this]([[maybe_unused]] AZ::EntityId entityId, const AZStd::string& gameLiftJsonString) { OnJSONChanged(gameLiftJsonString); });
  62. // Hide the attempting connection ui until the player tries to connect
  63. UiElementBus::Event(m_attemptConnectionBlockerUi, &UiElementInterface::SetIsEnabled, false);
  64. // Listen for disconnect events to know if connecting to the host server failed
  65. AZ::Interface<Multiplayer::IMultiplayer>::Get()->AddEndpointDisconnectedHandler(m_onConnectToHostFailed);
  66. UiElementBus::Event(m_jsonParseFailTextUi, &UiElementInterface::SetIsEnabled, true);
  67. UiTextBus::Event(m_jsonParseFailTextUi, &UiTextInterface::SetText, "");
  68. UiInteractableBus::Event(m_connectButtonUi, &UiInteractableInterface::SetIsHandlingEvents, false);
  69. OnJSONChanged("");
  70. }
  71. void UiGameLiftConnectWithPlayerSessionData::Deactivate()
  72. {
  73. m_onConnectToHostFailed.Disconnect();
  74. UiCursorBus::Broadcast(&UiCursorInterface::DecrementVisibleCounter);
  75. }
  76. void UiGameLiftConnectWithPlayerSessionData::OnJSONChanged(const AZStd::string& gameLiftJsonString)
  77. {
  78. // Disable the connect button until checking to make sure the user has provided the proper GameLift information in JSON format
  79. UiInteractableBus::Event(m_connectButtonUi, &UiInteractableInterface::SetIsHandlingEvents, false);
  80. if (gameLiftJsonString.empty())
  81. {
  82. UiTextBus::Event(m_jsonParseFailTextUi, &UiTextInterface::SetText, "Please provide GameLift player connection information in JSON format!");
  83. return;
  84. }
  85. // Parse GameLift JSON
  86. m_sessionConnectionConfig = {};
  87. rapidjson::Document document;
  88. document.Parse(gameLiftJsonString.c_str());
  89. if (document.HasParseError())
  90. {
  91. UiTextBus::Event(m_jsonParseFailTextUi, &UiTextInterface::SetText, "Invalid JSON format!");
  92. return;
  93. }
  94. // Alert the user if any information is missing from the JSON they provided
  95. if (!document.HasMember("PlayerSessionId"))
  96. {
  97. UiTextBus::Event(m_jsonParseFailTextUi, &UiTextInterface::SetText, "Missing PlayerSessionId!");
  98. return;
  99. }
  100. if (!document.HasMember("IpAddress") && !document.HasMember("DnsName"))
  101. {
  102. UiTextBus::Event(m_jsonParseFailTextUi, &UiTextInterface::SetText, "Must provide either an IpAddress or DnsName!");
  103. return;
  104. }
  105. if (!document.HasMember("Port"))
  106. {
  107. UiTextBus::Event(m_jsonParseFailTextUi, &UiTextInterface::SetText, "Missing Port!");
  108. return;
  109. }
  110. const rapidjson::Value& port = document["Port"];
  111. if (!port.IsUint())
  112. {
  113. UiTextBus::Event(m_jsonParseFailTextUi, &UiTextInterface::SetText, "Invalid Port!");
  114. return;
  115. }
  116. // Fill out SessionConnectionConfig and try connecting to host
  117. if (document.HasMember("IpAddress"))
  118. {
  119. const rapidjson::Value& ipAddress = document["IpAddress"];
  120. m_sessionConnectionConfig.m_ipAddress = ipAddress.GetString();
  121. }
  122. if (document.HasMember("DnsName"))
  123. {
  124. const rapidjson::Value& dnsName = document["DnsName"];
  125. m_sessionConnectionConfig.m_dnsName = dnsName.GetString();
  126. }
  127. const rapidjson::Value& playerSessionId = document["PlayerSessionId"];
  128. m_sessionConnectionConfig.m_port = aznumeric_cast<uint16_t>(port.GetUint());
  129. m_sessionConnectionConfig.m_playerSessionId = playerSessionId.GetString();
  130. UiTextBus::Event(m_jsonParseFailTextUi, &UiTextInterface::SetText, "");
  131. UiInteractableBus::Event(m_connectButtonUi, &UiInteractableInterface::SetIsHandlingEvents, true);
  132. }
  133. void UiGameLiftConnectWithPlayerSessionData::OnButtonClicked(AZ::EntityId buttonEntityId) const
  134. {
  135. const auto console = AZ::Interface<AZ::IConsole>::Get();
  136. if (!console)
  137. {
  138. AZ_Assert(false, "UiGameLiftConnectWithPlayerSessionData attempting to use console commands before AZ::Console is available.");
  139. return;
  140. }
  141. if (buttonEntityId == m_quitButtonUi)
  142. {
  143. console->PerformCommand("quit");
  144. return;
  145. }
  146. if (buttonEntityId == m_connectButtonUi)
  147. {
  148. // Enable blocker ui while we attempt connection
  149. UiElementBus::Event(m_attemptConnectionBlockerUi, &UiElementInterface::SetIsEnabled, true);
  150. if (auto clientRequestHandler = AZ::Interface<Multiplayer::ISessionHandlingClientRequests>::Get())
  151. {
  152. clientRequestHandler->RequestPlayerJoinSession(m_sessionConnectionConfig);
  153. }
  154. else
  155. {
  156. AZ_Assert(false, "UiGameLiftConnectWithPlayerSessionData failed to connect because there's no ISessionHandlingClientRequests registered. "
  157. "Please update code to ensure an ISessionHandlingClientRequests has been created before trying to connect this client to a host!");
  158. }
  159. }
  160. if (buttonEntityId == m_connectToHostFailedUi)
  161. {
  162. // Player acknowledged connection failed. Close the warning popup.
  163. UiElementBus::Event(m_connectToHostFailedUi, &UiElementInterface::SetIsEnabled, false);
  164. }
  165. }
  166. void UiGameLiftConnectWithPlayerSessionData::OnConnectToHostFailed()
  167. {
  168. UiElementBus::Event(m_attemptConnectionBlockerUi, &UiElementInterface::SetIsEnabled, false);
  169. UiElementBus::Event(m_connectToHostFailedUi, &UiElementInterface::SetIsEnabled, true);
  170. }
  171. } // namespace MultiplayerSample