NetworkDebugPlayerIdComponent.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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 <Multiplayer/Components/NetworkDebugPlayerIdComponent.h>
  9. #include <Multiplayer/ConnectionData/IConnectionData.h>
  10. #include <Atom/RPI.Public/ViewportContextBus.h>
  11. #include <AzCore/Component/TransformBus.h>
  12. #include <AzCore/Serialization/SerializeContext.h>
  13. #include <AzFramework/Viewport/ViewportScreen.h>
  14. #include <AzNetworking/Framework/INetworking.h>
  15. namespace Multiplayer
  16. {
  17. AZ_CVAR(bool, cl_debugPlayerIdRender, true, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Whether NetworkDebugPlayerIdComponent should render the player id and connection count on-screen.");
  18. void NetworkDebugPlayerIdComponent::Reflect(AZ::ReflectContext* context)
  19. {
  20. if (const auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  21. {
  22. serializeContext->Class<NetworkDebugPlayerIdComponent, NetworkDebugPlayerIdComponentBase>()
  23. ->Version(1)
  24. ->Field("translationOffset", &NetworkDebugPlayerIdComponent::m_translationOffset)
  25. ->Field("scale", &NetworkDebugPlayerIdComponent::m_fontScale)
  26. ->Field("color", &NetworkDebugPlayerIdComponent::m_fontColor)
  27. ;
  28. if (AZ::EditContext* editContext = serializeContext->GetEditContext())
  29. {
  30. editContext->Class<NetworkDebugPlayerIdComponent>("Network Debug Player ID", "Renders the player id as debug text over network players.")
  31. ->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  32. ->Attribute(AZ::Edit::Attributes::Category, "Multiplayer")
  33. ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game"))
  34. ->DataElement(AZ::Edit::UIHandlers::Default, &NetworkDebugPlayerIdComponent::m_translationOffset, "Translation Offset", "The world-space offset from the player position to render the debug text.")
  35. ->DataElement(AZ::Edit::UIHandlers::Default, &NetworkDebugPlayerIdComponent::m_fontScale, "Font Scale", "Apply a scale to the default debug font rendering size.")
  36. ->DataElement(AZ::Edit::UIHandlers::Color, &NetworkDebugPlayerIdComponent::m_fontColor, "Color", "Debug text color.")
  37. ;
  38. }
  39. }
  40. NetworkDebugPlayerIdComponentBase::Reflect(context);
  41. }
  42. void NetworkDebugPlayerIdComponent::OnActivate([[maybe_unused]] EntityIsMigrating entityIsMigrating)
  43. {
  44. #if (AZ_TRAIT_CLIENT)
  45. m_viewport = AZ::RPI::ViewportContextRequests::Get()->GetDefaultViewportContext();
  46. if (!m_viewport)
  47. {
  48. AZ_Assert(false, "NetworkDebugPlayerIdComponent failed to find the a rendering viewport. Debug rendering will be disabled.");
  49. return;
  50. }
  51. const auto fontQueryInterface = AZ::Interface<AzFramework::FontQueryInterface>::Get();
  52. if (!fontQueryInterface)
  53. {
  54. AZ_Assert(false, "NetworkDebugPlayerIdComponent failed to find the FontQueryInterface. Debug rendering will be disabled.");
  55. return;
  56. }
  57. m_fontDrawInterface = fontQueryInterface->GetDefaultFontDrawInterface();
  58. if (!m_fontDrawInterface)
  59. {
  60. AZ_Assert(false, "NetworkDebugPlayerIdComponent failed to find the FontDrawInterface. Debug rendering will be disabled.");
  61. return;
  62. }
  63. m_drawParams.m_drawViewportId = m_viewport->GetId();
  64. m_drawParams.m_scale = AZ::Vector2(m_fontScale);
  65. m_drawParams.m_color = m_fontColor;
  66. AZ::TickBus::Handler::BusConnect();
  67. #endif
  68. }
  69. void NetworkDebugPlayerIdComponent::OnDeactivate([[maybe_unused]] EntityIsMigrating entityIsMigrating)
  70. {
  71. AZ::TickBus::Handler::BusDisconnect();
  72. }
  73. #if AZ_TRAIT_SERVER
  74. void NetworkDebugPlayerIdComponent::SetOwningConnectionId(AzNetworking::ConnectionId connectionId)
  75. {
  76. if (IsNetEntityRoleAuthority())
  77. {
  78. const auto controller = static_cast<NetworkDebugPlayerIdComponentController*>(GetController());
  79. controller->SetPlayerId(connectionId);
  80. }
  81. }
  82. #endif
  83. void NetworkDebugPlayerIdComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time)
  84. {
  85. if (!cl_debugPlayerIdRender)
  86. {
  87. return;
  88. }
  89. // Don't render others players' on-screen debug text if the player is behind the camera
  90. AZ::Vector3 renderWorldSpace = GetEntity()->GetTransform()->GetWorldTranslation() + m_translationOffset;
  91. if (!IsNetEntityRoleAutonomous())
  92. {
  93. AZ::Vector3 cameraForward = m_viewport->GetCameraTransform().GetBasisY();
  94. AZ::Vector3 cameraToPlayer = renderWorldSpace - m_viewport->GetCameraTransform().GetTranslation();
  95. if (cameraForward.Dot(cameraToPlayer) < 0.0f)
  96. {
  97. return;
  98. }
  99. }
  100. const AzFramework::WindowSize windowSize = m_viewport->GetViewportSize();
  101. AzFramework::ScreenPoint renderScreenpoint = AzFramework::WorldToScreen(
  102. renderWorldSpace, m_viewport->GetCameraViewMatrixAsMatrix3x4(), m_viewport->GetCameraProjectionMatrix(), AzFramework::ScreenSize(windowSize.m_width, windowSize.m_height));
  103. m_drawParams.m_hAlign = AzFramework::TextHorizontalAlignment::Center;
  104. m_drawParams.m_position = AZ::Vector3(aznumeric_cast<float>(renderScreenpoint.m_x), aznumeric_cast<float>(renderScreenpoint.m_y), 0.f);
  105. AZStd::string playerIdText = AZStd::string::format("Player %i", static_cast<uint32_t>(GetPlayerId()));
  106. m_fontDrawInterface->DrawScreenAlignedText2d(m_drawParams, playerIdText);
  107. if (IsNetEntityRoleAutonomous())
  108. {
  109. // Render connection count in the lower right-hand corner
  110. const float textHeight = m_fontDrawInterface->GetTextSize(m_drawParams, playerIdText).GetY();
  111. const float lineSpacing = 0.5f * textHeight;
  112. const AzFramework::WindowSize viewportSize = m_viewport->GetViewportSize();
  113. const AZ::Vector3 viewportConnectionBottomRightBorderPadding(-40.0f, -40.0f + textHeight + lineSpacing, 0.0f);
  114. m_drawParams.m_hAlign = AzFramework::TextHorizontalAlignment::Right;
  115. m_drawParams.m_position =
  116. AZ::Vector3(aznumeric_cast<float>(viewportSize.m_width), aznumeric_cast<float>(viewportSize.m_height), 1.0f) +
  117. AZ::Vector3(viewportConnectionBottomRightBorderPadding) * m_viewport->GetDpiScalingFactor();
  118. const auto controller = static_cast<NetworkDebugPlayerIdComponentController*>(GetController());
  119. AZStd::string playerCountText = AZStd::string::format("Player Count: %i", controller->GetConnectionCount());
  120. m_fontDrawInterface->DrawScreenAlignedText2d(m_drawParams, playerCountText);
  121. }
  122. }
  123. NetworkDebugPlayerIdComponentController::NetworkDebugPlayerIdComponentController(NetworkDebugPlayerIdComponent& parent)
  124. : NetworkDebugPlayerIdComponentControllerBase(parent)
  125. {
  126. }
  127. void NetworkDebugPlayerIdComponentController::OnActivate([[maybe_unused]] EntityIsMigrating entityIsMigrating)
  128. {
  129. # if AZ_TRAIT_SERVER
  130. if (IsNetEntityRoleAuthority())
  131. {
  132. m_networkInterface = AZ::Interface<AzNetworking::INetworking>::Get()->RetrieveNetworkInterface(AZ::Name(MpNetworkInterfaceName));
  133. UpdateClientConnectionCount();
  134. AZ::Interface<IMultiplayer>::Get()->AddConnectionAcquiredHandler(m_connectionAcquiredHandler);
  135. AZ::Interface<IMultiplayer>::Get()->AddEndpointDisconnectedHandler(m_endpointDisconnectedHandler);
  136. }
  137. #endif
  138. }
  139. void NetworkDebugPlayerIdComponentController::OnDeactivate([[maybe_unused]] EntityIsMigrating entityIsMigrating)
  140. {
  141. m_connectionAcquiredHandler.Disconnect();
  142. m_endpointDisconnectedHandler.Disconnect();
  143. }
  144. void NetworkDebugPlayerIdComponentController::UpdateClientConnectionCount()
  145. {
  146. if (IsNetEntityRoleAuthority())
  147. {
  148. uint32_t clientConnectionCount = 0;
  149. auto sendNetworkUpdates = [&clientConnectionCount](AzNetworking::IConnection& connection)
  150. {
  151. if (connection.GetUserData() != nullptr)
  152. {
  153. const auto connectionData = reinterpret_cast<IConnectionData*>(connection.GetUserData());
  154. if (connectionData->GetConnectionDataType() == ConnectionDataType::ServerToClient)
  155. {
  156. clientConnectionCount++;
  157. }
  158. }
  159. };
  160. m_networkInterface->GetConnectionSet().VisitConnections(sendNetworkUpdates);
  161. SetConnectionCount(clientConnectionCount);
  162. }
  163. }
  164. void NetworkDebugPlayerIdComponentController::OnConnectionAcquired()
  165. {
  166. uint32_t currentConnectionCount = m_networkInterface->GetConnectionSet().GetConnectionCount() + 1;
  167. SetConnectionCount(currentConnectionCount);
  168. }
  169. void NetworkDebugPlayerIdComponentController::OnEndpointDisconnected()
  170. {
  171. uint32_t currentConnectionCount = m_networkInterface->GetConnectionSet().GetConnectionCount() - 1;
  172. SetConnectionCount(currentConnectionCount);
  173. }
  174. } // namespace Multiplayer