LCOV - code coverage report
Current view: top level - source/simulation2/components - CCmpProjectileManager.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 41 166 24.7 %
Date: 2026-12-02 01:21:50 Functions: 11 17 64.7 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "ICmpProjectileManager.h"
      21             : 
      22             : #include "graphics/ModelAbstract.h"
      23             : #include "graphics/Unit.h"
      24             : #include "graphics/UnitManager.h"
      25             : #include "lib/posix/posix_types.h"
      26             : #include "maths/Fixed.h"
      27             : #include "maths/FixedVector3D.h"
      28             : #include "maths/Frustum.h"
      29             : #include "maths/Matrix3D.h"
      30             : #include "maths/Quaternion.h"
      31             : #include "maths/Vector3D.h"
      32             : #include "ps/CStr.h"
      33             : #include "renderer/Scene.h"
      34             : #include "simulation2/MessageTypes.h"
      35             : #include "simulation2/components/ICmpRangeManager.h"
      36             : #include "simulation2/components/ICmpTerrain.h"
      37             : #include "simulation2/helpers/Los.h"
      38             : #include "simulation2/system/Component.h"
      39             : #include "simulation2/system/Entity.h"
      40             : #include "simulation2/system/Message.h"
      41             : 
      42             : #include <cmath>
      43             : #include <cstddef>
      44             : #include <cstdint>
      45             : #include <string>
      46             : #include <utility>
      47             : #include <vector>
      48             : 
      49             : // Time (in seconds) before projectiles that stuck in the ground are destroyed
      50             : const static float PROJECTILE_DECAY_TIME = 30.f;
      51             : 
      52           7 : class CCmpProjectileManager final : public ICmpProjectileManager
      53             : {
      54             : public:
      55         137 :     static void ClassInit(CComponentManager& componentManager)
      56             :     {
      57         137 :         componentManager.SubscribeToMessageType(MT_Interpolate);
      58         137 :         componentManager.SubscribeToMessageType(MT_RenderSubmit);
      59             :     }
      60             : 
      61          14 :     DEFAULT_COMPONENT_ALLOCATOR(ProjectileManager)
      62             : 
      63         137 :     static std::string GetSchema()
      64             :     {
      65         274 :         return "<a:component type='system'/><empty/>";
      66             :     }
      67             : 
      68           7 :     void Init(const CParamNode&) override
      69             :     {
      70           7 :         m_ActorSeed = 0;
      71           7 :         m_NextId = 1;
      72           7 :     }
      73             : 
      74           7 :     void Deinit() override
      75             :     {
      76           7 :         for (size_t i = 0; i < m_Projectiles.size(); ++i)
      77           0 :             GetSimContext().GetUnitManager().DeleteUnit(m_Projectiles[i].unit);
      78           7 :         m_Projectiles.clear();
      79           7 :     }
      80             : 
      81          18 :     void Serialize(ISerializer& serialize) override
      82             :     {
      83             :         // Because this is just graphical effects, and because it's all non-deterministic floating point,
      84             :         // we don't do much serialization here.
      85             :         // (That means projectiles will vanish if you save/load - is that okay?)
      86             : 
      87             :         // The attack code stores the id so that the projectile gets deleted when it hits the target
      88          18 :         serialize.NumberU32_Unbounded("next id", m_NextId);
      89          18 :     }
      90             : 
      91           0 :     void Deserialize(const CParamNode& paramNode, IDeserializer& deserialize) override
      92             :     {
      93           0 :         Init(paramNode);
      94             : 
      95             :         // The attack code stores the id so that the projectile gets deleted when it hits the target
      96           0 :         deserialize.NumberU32_Unbounded("next id", m_NextId);
      97           0 :     }
      98             : 
      99           3 :     void HandleMessage(const CMessage& msg, bool /*global*/) override
     100             :     {
     101           3 :         switch (msg.GetType())
     102             :         {
     103           3 :         case MT_Interpolate:
     104           3 :         {
     105           3 :             const CMessageInterpolate& msgData = static_cast<const CMessageInterpolate&> (msg);
     106           3 :             Interpolate(msgData.deltaSimTime);
     107           3 :             break;
     108             :         }
     109           0 :         case MT_RenderSubmit:
     110           0 :         {
     111           0 :             const CMessageRenderSubmit& msgData = static_cast<const CMessageRenderSubmit&> (msg);
     112           0 :             RenderSubmit(msgData.collector, msgData.frustum, msgData.culling);
     113           0 :             break;
     114             :         }
     115             :         }
     116           3 :     }
     117             : 
     118         120 :     uint32_t LaunchProjectileAtPoint(const CFixedVector3D& launchPoint, const CFixedVector3D& target, fixed speed, fixed gravity, const std::wstring& actorName, const std::wstring& impactActorName, fixed impactAnimationLifetime) override
     119             :     {
     120         120 :         return LaunchProjectile(launchPoint, target, speed, gravity, actorName, impactActorName, impactAnimationLifetime);
     121             :     }
     122             : 
     123             :     void RemoveProjectile(uint32_t) override;
     124             : 
     125             :     void RenderModel(CModelAbstract& model, const CVector3D& position, SceneCollector& collector, const CFrustum& frustum, bool culling,
     126             :         const CLosQuerier& los, bool losRevealWholeMap) const;
     127             : 
     128             : private:
     129           0 :     struct Projectile
     130             :     {
     131             :         CUnit* unit;
     132             :         CVector3D origin;
     133             :         CVector3D pos;
     134             :         CVector3D v;
     135             :         float time;
     136             :         float timeHit;
     137             :         float gravity;
     138             :         float impactAnimationLifetime;
     139             :         uint32_t id;
     140             :         std::wstring impactActorName;
     141             :         bool isImpactAnimationCreated;
     142             :         bool stopped;
     143             : 
     144           0 :         CVector3D position(float t)
     145             :         {
     146           0 :             float t2 = t;
     147           0 :             if (t2 > timeHit)
     148           0 :                 t2 = timeHit + logf(1.f + t2 - timeHit);
     149             : 
     150           0 :             CVector3D ret(origin);
     151           0 :             ret.X += v.X * t2;
     152           0 :             ret.Z += v.Z * t2;
     153           0 :             ret.Y += v.Y * t2 - 0.5f * gravity * t * t;
     154           0 :             return ret;
     155             :         }
     156             :     };
     157             : 
     158           0 :     struct ProjectileImpactAnimation
     159             :     {
     160             :         CUnit* unit;
     161             :         CVector3D pos;
     162             :         float time;
     163             :     };
     164             : 
     165             :     std::vector<Projectile> m_Projectiles;
     166             : 
     167             :     std::vector<ProjectileImpactAnimation> m_ProjectileImpactAnimations;
     168             : 
     169             :     uint32_t m_ActorSeed;
     170             : 
     171             :     uint32_t m_NextId;
     172             : 
     173             :     uint32_t LaunchProjectile(CFixedVector3D launchPoint, CFixedVector3D targetPoint, fixed speed, fixed gravity,
     174             :         const std::wstring& actorName, const std::wstring& impactActorName, fixed impactAnimationLifetime);
     175             : 
     176             :     void AdvanceProjectile(Projectile& projectile, float dt) const;
     177             : 
     178             :     void Interpolate(float frameTime);
     179             : 
     180             :     void RenderSubmit(SceneCollector& collector, const CFrustum& frustum, bool culling) const;
     181             : };
     182             : 
     183         411 : REGISTER_COMPONENT_TYPE(ProjectileManager)
     184             : 
     185         120 : uint32_t CCmpProjectileManager::LaunchProjectile(CFixedVector3D launchPoint, CFixedVector3D targetPoint, fixed speed, fixed gravity, const std::wstring& actorName, const std::wstring& impactActorName, fixed impactAnimationLifetime)
     186             : {
     187             :     // This is network synced so don't use GUI checks before incrementing or it breaks any non GUI simulations
     188         120 :     uint32_t currentId = m_NextId++;
     189             : 
     190         120 :     if (!GetSimContext().HasUnitManager() || actorName.empty())
     191             :         return currentId; // do nothing if graphics are disabled
     192             : 
     193           0 :     Projectile projectile;
     194           0 :     projectile.id = currentId;
     195           0 :     projectile.time = 0.f;
     196           0 :     projectile.stopped = false;
     197           0 :     projectile.gravity = gravity.ToFloat();
     198           0 :     projectile.isImpactAnimationCreated = false;
     199             : 
     200           0 :     if (!impactActorName.empty())
     201             :     {
     202           0 :         projectile.impactActorName = impactActorName;
     203           0 :         projectile.impactAnimationLifetime = impactAnimationLifetime.ToFloat();
     204             :     }
     205             :     else
     206             :     {
     207           0 :         projectile.impactActorName = L"";
     208           0 :         projectile.impactAnimationLifetime = 0.0f;
     209             :     }
     210             : 
     211           0 :     projectile.origin = launchPoint;
     212             : 
     213           0 :     projectile.unit = GetSimContext().GetUnitManager().CreateUnit(actorName, INVALID_ENTITY, m_ActorSeed++);
     214           0 :     if (!projectile.unit) // The error will have already been logged
     215             :         return currentId;
     216             : 
     217           0 :     projectile.pos = projectile.origin;
     218           0 :     CVector3D offset(targetPoint);
     219           0 :     offset -= projectile.pos;
     220           0 :     float horizDistance = sqrtf(offset.X*offset.X + offset.Z*offset.Z);
     221           0 :     projectile.timeHit = horizDistance / speed.ToFloat();
     222           0 :     projectile.v = offset * (1.f / projectile.timeHit);
     223             : 
     224           0 :     projectile.v.Y = offset.Y / projectile.timeHit  + 0.5f * projectile.gravity * projectile.timeHit;
     225             : 
     226           0 :     m_Projectiles.push_back(projectile);
     227             : 
     228           0 :     return projectile.id;
     229         120 : }
     230             : 
     231           0 : void CCmpProjectileManager::AdvanceProjectile(Projectile& projectile, float dt) const
     232             : {
     233           0 :     projectile.time += dt;
     234           0 :     if (projectile.stopped)
     235           0 :         return;
     236             : 
     237           0 :     CVector3D delta;
     238           0 :     if (dt < 0.1f)
     239           0 :         delta = projectile.pos;
     240             :     else // For big dt delta is unprecise
     241           0 :         delta = projectile.position(projectile.time - 0.1f);
     242             : 
     243           0 :     projectile.pos = projectile.position(projectile.time);
     244             : 
     245           0 :     delta = projectile.pos - delta;
     246             : 
     247             :     // If we've passed the target position and haven't stopped yet,
     248             :     // carry on until we reach solid land
     249           0 :     if (projectile.time >= projectile.timeHit)
     250             :     {
     251           0 :         CmpPtr<ICmpTerrain> cmpTerrain(GetSystemEntity());
     252           0 :         if (cmpTerrain)
     253             :         {
     254           0 :             float h = cmpTerrain->GetExactGroundLevel(projectile.pos.X, projectile.pos.Z);
     255           0 :             if (projectile.pos.Y < h)
     256             :             {
     257           0 :                 projectile.pos.Y = h; // stick precisely to the terrain
     258           0 :                 projectile.stopped = true;
     259             :             }
     260             :         }
     261             :     }
     262             : 
     263             :     // Construct a rotation matrix so that (0,1,0) is in the direction of 'delta'
     264             : 
     265           0 :     CVector3D up(0, 1, 0);
     266             : 
     267           0 :     delta.Normalize();
     268           0 :     CVector3D axis = up.Cross(delta);
     269           0 :     if (axis.LengthSquared() < 0.0001f)
     270           0 :         axis = CVector3D(1, 0, 0); // if up & delta are almost collinear, rotate around some other arbitrary axis
     271             :     else
     272           0 :         axis.Normalize();
     273             : 
     274           0 :     float angle = acosf(up.Dot(delta));
     275             : 
     276           0 :     CMatrix3D transform;
     277           0 :     CQuaternion quat;
     278           0 :     quat.FromAxisAngle(axis, angle);
     279           0 :     quat.ToMatrix(transform);
     280             : 
     281             :     // Then apply the translation
     282           0 :     transform.Translate(projectile.pos);
     283             : 
     284             :     // Move the model
     285           0 :     projectile.unit->GetModel().SetTransform(transform);
     286             : }
     287             : 
     288           3 : void CCmpProjectileManager::Interpolate(float frameTime)
     289             : {
     290           3 :     for (size_t i = 0; i < m_Projectiles.size(); ++i)
     291             :     {
     292           0 :         AdvanceProjectile(m_Projectiles[i], frameTime);
     293             :     }
     294             : 
     295             :     // Remove the ones that have reached their target
     296           3 :     for (size_t i = 0; i < m_Projectiles.size(); )
     297             :     {
     298           0 :         if (!m_Projectiles[i].stopped)
     299             :         {
     300           0 :             ++i;
     301           0 :             continue;
     302             :         }
     303             : 
     304           0 :         if (!m_Projectiles[i].impactActorName.empty() && !m_Projectiles[i].isImpactAnimationCreated)
     305             :         {
     306           0 :             m_Projectiles[i].isImpactAnimationCreated = true;
     307           0 :             CMatrix3D transform;
     308           0 :             CQuaternion quat;
     309           0 :             quat.ToMatrix(transform);
     310           0 :             transform.Translate(m_Projectiles[i].pos);
     311             : 
     312           0 :             CUnit* unit = GetSimContext().GetUnitManager().CreateUnit(m_Projectiles[i].impactActorName, INVALID_ENTITY, m_ActorSeed++);
     313           0 :             unit->GetModel().SetTransform(transform);
     314             : 
     315           0 :             ProjectileImpactAnimation projectileImpactAnimation;
     316           0 :             projectileImpactAnimation.unit = unit;
     317           0 :             projectileImpactAnimation.time = m_Projectiles[i].impactAnimationLifetime;
     318           0 :             projectileImpactAnimation.pos = m_Projectiles[i].pos;
     319           0 :             m_ProjectileImpactAnimations.push_back(projectileImpactAnimation);
     320             :         }
     321             : 
     322             :         // Projectiles hitting targets get removed immediately.
     323             :         // Those hitting the ground stay for a while, because it looks pretty.
     324           0 :         if (m_Projectiles[i].time - m_Projectiles[i].timeHit > PROJECTILE_DECAY_TIME)
     325             :         {
     326             :             // Delete in-place by swapping with the last in the list
     327           0 :             std::swap(m_Projectiles[i], m_Projectiles.back());
     328           0 :             GetSimContext().GetUnitManager().DeleteUnit(m_Projectiles.back().unit);
     329           0 :             m_Projectiles.pop_back();
     330           0 :             continue;
     331             :         }
     332           0 :         ++i;
     333             :     }
     334             : 
     335           3 :     for (size_t i = 0; i < m_ProjectileImpactAnimations.size();)
     336             :     {
     337           0 :         if (m_ProjectileImpactAnimations[i].time > 0)
     338             :         {
     339           0 :             m_ProjectileImpactAnimations[i].time -= frameTime;
     340           0 :             ++i;
     341             :         }
     342             :         else
     343             :         {
     344           0 :             std::swap(m_ProjectileImpactAnimations[i], m_ProjectileImpactAnimations.back());
     345           0 :             GetSimContext().GetUnitManager().DeleteUnit(m_ProjectileImpactAnimations.back().unit);
     346           3 :             m_ProjectileImpactAnimations.pop_back();
     347             :         }
     348             :     }
     349           3 : }
     350             : 
     351          57 : void CCmpProjectileManager::RemoveProjectile(uint32_t id)
     352             : {
     353             :     // Scan through the projectile list looking for one with the correct id to remove
     354          57 :     for (size_t i = 0; i < m_Projectiles.size(); i++)
     355             :     {
     356           0 :         if (m_Projectiles[i].id == id)
     357             :         {
     358             :             // Delete in-place by swapping with the last in the list
     359           0 :             std::swap(m_Projectiles[i], m_Projectiles.back());
     360           0 :             GetSimContext().GetUnitManager().DeleteUnit(m_Projectiles.back().unit);
     361           0 :             m_Projectiles.pop_back();
     362           0 :             return;
     363             :         }
     364             :     }
     365             : }
     366             : 
     367           0 : void CCmpProjectileManager::RenderModel(CModelAbstract& model, const CVector3D& position, SceneCollector& collector,
     368             :     const CFrustum& frustum, bool culling, const CLosQuerier& los, bool losRevealWholeMap) const
     369             : {
     370             :     // Don't display objects outside the visible area
     371           0 :     ssize_t posi = (ssize_t)(0.5f + position.X / LOS_TILE_SIZE);
     372           0 :     ssize_t posj = (ssize_t)(0.5f + position.Z / LOS_TILE_SIZE);
     373           0 :     if (!losRevealWholeMap && !los.IsVisible(posi, posj))
     374             :         return;
     375             : 
     376           0 :     model.ValidatePosition();
     377             : 
     378           0 :     if (culling && !frustum.IsBoxVisible(model.GetWorldBoundsRec()))
     379           0 :         return;
     380             : 
     381             :     // TODO: do something about LOS (copy from CCmpVisualActor)
     382             : 
     383           0 :     collector.SubmitRecursive(&model);
     384             : }
     385             : 
     386           0 : void CCmpProjectileManager::RenderSubmit(SceneCollector& collector, const CFrustum& frustum, bool culling) const
     387             : {
     388           0 :     CmpPtr<ICmpRangeManager> cmpRangeManager(GetSystemEntity());
     389           0 :     int player = GetSimContext().GetCurrentDisplayedPlayer();
     390           0 :     CLosQuerier los(cmpRangeManager->GetLosQuerier(player));
     391           0 :     bool losRevealWholeMap = cmpRangeManager->GetLosRevealWholeMap(player);
     392             : 
     393           0 :     for (const Projectile& projectile : m_Projectiles)
     394             :     {
     395           0 :         RenderModel(projectile.unit->GetModel(), projectile.pos, collector, frustum, culling, los, losRevealWholeMap);
     396             :     }
     397             : 
     398           0 :     for (const ProjectileImpactAnimation& projectileImpactAnimation : m_ProjectileImpactAnimations)
     399             :     {
     400           0 :         RenderModel(projectileImpactAnimation.unit->GetModel(), projectileImpactAnimation.pos,
     401             :             collector, frustum, culling, los, losRevealWholeMap);
     402             :     }
     403           0 : }

Generated by: LCOV version 1.16