EnergyBallComponent.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
  3. *
  4. * SPDX-License-Identifier: Apache-2.0 OR MIT
  5. *
  6. */
  7. #include <Source/Components/Multiplayer/EnergyBallComponent.h>
  8. #include <Source/AutoGen/NetworkHealthComponent.AutoComponent.h>
  9. #include <Multiplayer/Components/NetworkTransformComponent.h>
  10. #include <Multiplayer/Components/NetworkRigidBodyComponent.h>
  11. #include <MultiplayerSampleTypes.h>
  12. #include <AzCore/Component/TransformBus.h>
  13. #include <AzFramework/Physics/Components/SimulatedBodyComponentBus.h>
  14. #include <AzFramework/Physics/RigidBodyBus.h>
  15. #include <WeaponNotificationBus.h>
  16. #if AZ_TRAIT_CLIENT
  17. # include <PopcornFX/PopcornFXBus.h>
  18. # include <DebugDraw/DebugDrawBus.h>
  19. #endif
  20. namespace MultiplayerSample
  21. {
  22. AZ_CVAR(float, sv_EnergyBallImpulseScalar, 500.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "A fudge factor for imparting impulses on rigid bodies due to weapon hits");
  23. AZ_CVAR(bool, cl_EnergyBallDebugDraw, false, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "When turned on this will draw the current energy ball location");
  24. void EnergyBallComponent::Reflect(AZ::ReflectContext* context)
  25. {
  26. AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
  27. if (serializeContext)
  28. {
  29. serializeContext->Class<EnergyBallComponent, EnergyBallComponentBase>()
  30. ->Version(1);
  31. }
  32. EnergyBallComponentBase::Reflect(context);
  33. }
  34. void EnergyBallComponent::OnActivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating)
  35. {
  36. m_effect = GetExplosionEffect();
  37. m_effect.Initialize();
  38. #if AZ_TRAIT_CLIENT
  39. BallActiveAddEvent(m_ballActiveHandler);
  40. #endif
  41. }
  42. void EnergyBallComponent::OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating)
  43. {
  44. #if AZ_TRAIT_CLIENT
  45. m_ballActiveHandler.Disconnect();
  46. #endif
  47. }
  48. #if AZ_TRAIT_CLIENT
  49. void EnergyBallComponent::OnBallActiveChanged(bool active)
  50. {
  51. if (active)
  52. {
  53. bool startSuccess = false;
  54. // Set to true to call "Kill" which is deferred, or false to call "Terminate" which is immediate.
  55. constexpr bool KillOnRestart = true;
  56. PopcornFX::PopcornFXEmitterComponentRequestBus::EventResult(startSuccess,
  57. GetEntity()->GetId(), &PopcornFX::PopcornFXEmitterComponentRequestBus::Events::Restart, KillOnRestart);
  58. AZ_Error("EnergyBall", startSuccess, "Restart call for Energy Ball was unsuccessful.");
  59. if (cl_EnergyBallDebugDraw)
  60. {
  61. m_debugDrawEvent.Enqueue(AZ::TimeMs{ 0 }, true);
  62. }
  63. }
  64. else
  65. {
  66. bool killSuccess = false;
  67. // This would ideally use Kill instead of Terminate, but there is a bug in PopcornFX 2.15.4 that if Kill is
  68. // called on the first tick (which can happen), then the effect will get stuck in a permanent waiting-to-die state,
  69. // and no amount of Restart calls will ever make it show up again.
  70. PopcornFX::PopcornFXEmitterComponentRequestBus::EventResult(killSuccess,
  71. GetEntity()->GetId(), &PopcornFX::PopcornFXEmitterComponentRequestBus::Events::Terminate);
  72. AZ_Error("EnergyBall", killSuccess, "Kill call for Energy Ball was unsuccessful.");
  73. m_debugDrawEvent.RemoveFromQueue();
  74. }
  75. }
  76. void EnergyBallComponent::HandleRPC_BallExplosion([[maybe_unused]] AzNetworking::IConnection* invokingConnection, const HitEvent& hitEvent)
  77. {
  78. // Crate an explosion effect wherever the ball was last at.
  79. AZ::Transform transform = AZ::Transform::CreateFromQuaternionAndTranslation(AZ::Quaternion::CreateIdentity(), hitEvent.m_target);
  80. m_effect.TriggerEffect(transform);
  81. // Notify every entity that was hit that they've received a weapon impact.
  82. for (const HitEntity& hitEntity : hitEvent.m_hitEntities)
  83. {
  84. const AZ::Transform hitTransform = AZ::Transform::CreateLookAt(hitEntity.m_hitPosition, hitEntity.m_hitPosition + hitEntity.m_hitNormal, AZ::Transform::Axis::ZPositive);
  85. const Multiplayer::ConstNetworkEntityHandle handle = Multiplayer::GetNetworkEntityManager()->GetEntity(hitEntity.m_hitNetEntityId);
  86. const AZ::EntityId hitEntityId = handle.Exists() ? handle.GetEntity()->GetId() : AZ::EntityId();
  87. WeaponNotificationBus::Broadcast(&WeaponNotificationBus::Events::OnWeaponImpact, GetEntity()->GetId(), hitTransform, hitEntityId);
  88. }
  89. }
  90. void EnergyBallComponent::DebugDraw()
  91. {
  92. if (cl_EnergyBallDebugDraw)
  93. {
  94. // Each draw only lasts one frame.
  95. constexpr float DrawDuration = 0.0f;
  96. auto* shapeConfig = GetGatherParams().GetCurrentShapeConfiguration();
  97. if (shapeConfig->GetShapeType() == Physics::ShapeType::Sphere)
  98. {
  99. const Physics::SphereShapeConfiguration* sphere = static_cast<const Physics::SphereShapeConfiguration*>(shapeConfig);
  100. float debugRadius = sphere->m_radius;
  101. DebugDraw::DebugDrawRequestBus::Broadcast(
  102. &DebugDraw::DebugDrawRequestBus::Events::DrawSphereAtLocation,
  103. GetEntity()->GetTransform()->GetWorldTM().GetTranslation(),
  104. debugRadius,
  105. AZ::Colors::Green,
  106. DrawDuration
  107. );
  108. }
  109. else if (shapeConfig->GetShapeType() == Physics::ShapeType::Box)
  110. {
  111. const Physics::BoxShapeConfiguration* box = static_cast<const Physics::BoxShapeConfiguration*>(shapeConfig);
  112. AZ::Obb obb = AZ::Obb::CreateFromPositionRotationAndHalfLengths(
  113. GetEntity()->GetTransform()->GetWorldTM().GetTranslation(),
  114. GetEntity()->GetTransform()->GetWorldTM().GetRotation(),
  115. box->m_dimensions / 2.0f
  116. );
  117. DebugDraw::DebugDrawRequestBus::Broadcast(
  118. &DebugDraw::DebugDrawRequestBus::Events::DrawObb,
  119. obb,
  120. AZ::Colors::Green,
  121. DrawDuration
  122. );
  123. }
  124. else if (shapeConfig->GetShapeType() == Physics::ShapeType::Capsule)
  125. {
  126. AZ_Error("EnergyBall", false, "Capsule shape type not currently supported with energy ball debug visualization.");
  127. }
  128. }
  129. }
  130. #endif
  131. EnergyBallComponentController::EnergyBallComponentController(EnergyBallComponent& parent)
  132. : EnergyBallComponentControllerBase(parent)
  133. {
  134. }
  135. void EnergyBallComponentController::OnActivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating)
  136. {
  137. #if AZ_TRAIT_SERVER
  138. SetBallActive(false);
  139. #endif
  140. }
  141. void EnergyBallComponentController::OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating)
  142. {
  143. #if AZ_TRAIT_SERVER
  144. SetBallActive(false);
  145. #endif
  146. }
  147. #if AZ_TRAIT_SERVER
  148. void EnergyBallComponentController::HandleRPC_LaunchBall(AzNetworking::IConnection* invokingConnection, const AZ::Vector3& startingPosition, const AZ::Vector3& direction, const Multiplayer::NetEntityId& owningNetEntityId)
  149. {
  150. if (GetBallActive())
  151. {
  152. return;
  153. }
  154. m_collisionCheckEvent.Enqueue(AZ::TimeMs{ 10 }, true);
  155. SetBallActive(true);
  156. m_shooterNetEntityId = owningNetEntityId;
  157. m_hitEvent.m_hitEntities.clear();
  158. m_filteredNetEntityIds.clear();
  159. m_filteredNetEntityIds.insert(owningNetEntityId);
  160. m_filteredNetEntityIds.insert(GetNetEntityId());
  161. m_direction = direction;
  162. // Move the entity to the start position
  163. GetNetworkTransformComponentController()->HandleMultiplayerTeleport(invokingConnection, startingPosition);
  164. // We want to sweep our transform during intersect tests to avoid the ball tunneling through targets
  165. m_lastSweepTransform = GetEntity()->GetTransform()->GetWorldTM();
  166. AzPhysics::SimulatedBodyComponentRequestsBus::Event(GetEntityId(), &AzPhysics::SimulatedBodyComponentRequestsBus::Events::EnablePhysics);
  167. Physics::RigidBodyRequestBus::Event(GetEntityId(), &Physics::RigidBodyRequestBus::Events::SetLinearVelocity, direction * GetGatherParams().m_travelSpeed);
  168. }
  169. void EnergyBallComponentController::HandleRPC_KillBall([[maybe_unused]] AzNetworking::IConnection* invokingConnection)
  170. {
  171. HideEnergyBall();
  172. }
  173. void EnergyBallComponentController::CheckForCollisions()
  174. {
  175. if (!GetBallActive())
  176. {
  177. return;
  178. }
  179. const AZ::Vector3& position = GetEntity()->GetTransform()->GetWorldTM().GetTranslation();
  180. const HitEffect& effect = GetHitEffect();
  181. // Sweep from our last checked transform to our current position to avoid tunneling
  182. const ActivateEvent activateEvent{ m_lastSweepTransform, position, m_shooterNetEntityId, GetNetEntityId() };
  183. IntersectResults results;
  184. GatherEntities(GetGatherParams(), activateEvent, m_filteredNetEntityIds, results);
  185. if (!results.empty())
  186. {
  187. for (const IntersectResult& result : results)
  188. {
  189. const HitEntity hitEntity{ result.m_position, result.m_normal, result.m_netEntityId };
  190. m_hitEvent.m_hitEntities.emplace_back(hitEntity);
  191. const Multiplayer::ConstNetworkEntityHandle handle = Multiplayer::GetNetworkEntityManager()->GetEntity(result.m_netEntityId);
  192. if (handle.Exists())
  193. {
  194. // Presently set to 1 until we capture falloff range
  195. float hitDistance = 1.f;
  196. float maxDistance = 1.f;
  197. float damage = effect.m_hitMagnitude * powf((effect.m_hitFalloff * (1.0f - hitDistance / maxDistance)), effect.m_hitExponent);
  198. // Look for physics rigid body component and make impact updates
  199. if (Multiplayer::NetworkRigidBodyComponent* rigidBodyComponent = handle.GetEntity()->FindComponent<Multiplayer::NetworkRigidBodyComponent>())
  200. {
  201. const AZ::Vector3 explosionCentre = position;
  202. const AZ::Vector3 hitObject = handle.GetEntity()->GetTransform()->GetWorldTM().GetTranslation();
  203. const AZ::Vector3 impulse = (hitObject - position).GetNormalized() * damage * sv_EnergyBallImpulseScalar;
  204. rigidBodyComponent->SendApplyImpulse(impulse, position);
  205. }
  206. // Look for health component and directly update health based on hit parameters
  207. if (NetworkHealthComponent* healthComponent = handle.GetEntity()->FindComponent<NetworkHealthComponent>())
  208. {
  209. healthComponent->SendHealthDelta(damage * -1.0f);
  210. }
  211. }
  212. }
  213. HideEnergyBall();
  214. }
  215. // Update our last sweep transform for the next time we check collision
  216. m_lastSweepTransform = GetEntity()->GetTransform()->GetWorldTM();
  217. }
  218. void EnergyBallComponentController::HideEnergyBall()
  219. {
  220. if (!GetBallActive())
  221. {
  222. return;
  223. }
  224. SetBallActive(false);
  225. m_collisionCheckEvent.RemoveFromQueue();
  226. m_hitEvent.m_target = GetEntity()->GetTransform()->GetWorldTM().GetTranslation();
  227. m_hitEvent.m_shooterNetEntityId = m_shooterNetEntityId;
  228. m_hitEvent.m_projectileNetEntityId = GetNetEntityId();
  229. AzPhysics::SimulatedBodyComponentRequestsBus::Event(GetEntityId(), &AzPhysics::SimulatedBodyComponentRequestsBus::Events::DisablePhysics);
  230. Physics::RigidBodyRequestBus::Event(GetEntityId(), &Physics::RigidBodyRequestBus::Events::SetLinearVelocity, AZ::Vector3::CreateZero());
  231. RPC_BallExplosion(m_hitEvent);
  232. }
  233. #endif
  234. }