LCOV - code coverage report
Current view: top level - source/simulation2/components - CCmpPathfinder_Common.h (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 35 39 89.7 %
Date: 2026-12-02 01:21:50 Functions: 9 12 75.0 %

          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             : #ifndef INCLUDED_CCMPPATHFINDER_COMMON
      19             : #define INCLUDED_CCMPPATHFINDER_COMMON
      20             : 
      21             : /**
      22             :  * @file
      23             :  * Declares CCmpPathfinder. Its implementation is mainly done in CCmpPathfinder.cpp,
      24             :  * but the short-range (vertex) pathfinding is done in CCmpPathfinder_Vertex.cpp.
      25             :  * This file provides common code needed for both files.
      26             :  *
      27             :  * The long-range pathfinding is done by a LongPathfinder object.
      28             :  */
      29             : 
      30             : #include "graphics/Overlay.h"
      31             : #include "graphics/SColor.h"
      32             : #include "maths/Fixed.h"
      33             : #include "ps/Future.h"
      34             : #include "renderer/TerrainOverlay.h"
      35             : #include "simulation2/components/ICmpObstruction.h"
      36             : #include "simulation2/components/ICmpPathfinder.h"
      37             : #include "simulation2/helpers/Grid.h"
      38             : #include "simulation2/helpers/HierarchicalPathfinder.h"
      39             : #include "simulation2/helpers/LongPathfinder.h"
      40             : #include "simulation2/helpers/Pathfinding.h"
      41             : #include "simulation2/helpers/Position.h"
      42             : #include "simulation2/helpers/VertexPathfinder.h"
      43             : #include "simulation2/system/Component.h"
      44             : #include "simulation2/system/Entity.h"
      45             : 
      46             : #include <atomic>
      47             : #include <cstddef>
      48             : #include <map>
      49             : #include <memory>
      50             : #include <string>
      51             : #include <vector>
      52             : 
      53             : class SceneCollector;
      54             : 
      55             : #ifdef NDEBUG
      56             : #define PATHFIND_DEBUG 0
      57             : #else
      58             : #define PATHFIND_DEBUG 1
      59             : #endif
      60             : 
      61             : /**
      62             :  * Implementation of ICmpPathfinder
      63             :  */
      64             : class CCmpPathfinder final : public ICmpPathfinder
      65             : {
      66             : public:
      67         137 :     static void ClassInit(CComponentManager& componentManager)
      68             :     {
      69         137 :         componentManager.SubscribeToMessageType(MT_Deserialized);
      70         137 :         componentManager.SubscribeToMessageType(MT_RenderSubmit); // for debug overlays
      71         137 :         componentManager.SubscribeToMessageType(MT_TerrainChanged);
      72         137 :         componentManager.SubscribeToMessageType(MT_WaterChanged);
      73         137 :         componentManager.SubscribeToMessageType(MT_ObstructionMapShapeChanged);
      74         137 :     }
      75             : 
      76             :     ~CCmpPathfinder();
      77             : 
      78          14 :     DEFAULT_COMPONENT_ALLOCATOR(Pathfinder)
      79             : 
      80             :     // Template state:
      81             : 
      82             :     std::map<std::string, pass_class_t> m_PassClassMasks;
      83             :     std::vector<PathfinderPassability> m_PassClasses;
      84             :     std::uint16_t m_MaxSameTurnMoves; // Compute only this many paths when useMax is true in StartProcessingMoves.
      85             : 
      86             :     // Dynamic state:
      87             : 
      88             :     // Lazily-constructed dynamic state (not serialized):
      89             : 
      90             :     std::uint16_t m_GridSize; // Navcells per side of the map.
      91             :     Grid<NavcellData>* m_Grid; // terrain/passability information
      92             :     Grid<NavcellData>* m_TerrainOnlyGrid; // same as m_Grid, but only with terrain, to avoid some recomputations
      93             : 
      94             :     // Keep clever updates in memory to avoid memory fragmentation from the grid.
      95             :     // This should be used only in UpdateGrid(), there is no guarantee the data is properly initialized anywhere else.
      96             :     GridUpdateInformation m_DirtinessInformation;
      97             :     // The data from clever updates is stored for the AI manager
      98             :     GridUpdateInformation m_AIPathfinderDirtinessInformation;
      99             :     bool m_TerrainDirty;
     100             : 
     101             :     std::vector<VertexPathfinder> m_VertexPathfinders;
     102             :     std::unique_ptr<HierarchicalPathfinder> m_PathfinderHier;
     103             :     std::unique_ptr<LongPathfinder> m_LongPathfinder;
     104             : 
     105             :     // One per live asynchronous path computing task.
     106             :     std::vector<Future<void>> m_Futures;
     107             : 
     108             :     template<typename T>
     109             :     class PathRequests {
     110             :     public:
     111             :         std::vector<T> m_Requests;
     112             :         std::vector<PathResult> m_Results;
     113             :         // This is the array index of the next path to compute.
     114             :         std::atomic<size_t> m_NextPathToCompute = 0;
     115             :         // This is false until all scheduled paths have been computed.
     116             :         std::atomic<bool> m_ComputeDone = true;
     117             : 
     118        1080 :         void ClearComputed()
     119             :         {
     120        1080 :             if (m_Results.size() == m_Requests.size())
     121        1077 :                 m_Requests.clear();
     122             :             else
     123           3 :                 m_Requests.erase(m_Requests.end() - m_Results.size(), m_Requests.end());
     124        1080 :             m_Results.clear();
     125        1080 :         }
     126             : 
     127             :         /**
     128             :          * @param max - if non-zero, how many paths to process.
     129             :          */
     130        1080 :         void PrepareForComputation(std::uint16_t max)
     131             :         {
     132        1080 :             size_t n = m_Requests.size();
     133        1080 :             if (max && n > max)
     134        1080 :                 n = max;
     135        1080 :             m_NextPathToCompute = 0;
     136        1080 :             m_Results.resize(n);
     137        1080 :             m_ComputeDone = n == 0;
     138        1080 :         }
     139             : 
     140             :         template<typename U>
     141             :         void Compute(const CCmpPathfinder& cmpPathfinder, const U& pathfinder);
     142             :     };
     143             :     PathRequests<LongPathRequest> m_LongPathRequests;
     144             :     PathRequests<ShortPathRequest> m_ShortPathRequests;
     145             : 
     146             :     std::uint32_t m_NextAsyncTicket; // Unique IDs for asynchronous path requests.
     147             : 
     148             :     pass_class_t m_OverlayPassClass;
     149             :     TerrainTextureOverlay* m_AtlasOverlay;
     150             : 
     151         137 :     static std::string GetSchema()
     152             :     {
     153         137 :         return "<a:component type='system'/><empty/>";
     154             :     }
     155             : 
     156             :     void Init(const CParamNode& paramNode) override;
     157             : 
     158             :     void Deinit() override;
     159             : 
     160             :     template<typename S>
     161             :     void SerializeCommon(S& serialize);
     162             : 
     163             :     void Serialize(ISerializer& serialize) override;
     164             : 
     165             :     void Deserialize(const CParamNode& paramNode, IDeserializer& deserialize) override;
     166             : 
     167             :     void HandleMessage(const CMessage& msg, bool global) override;
     168             : 
     169             :     pass_class_t GetPassabilityClass(const std::string& name) const override;
     170             : 
     171             :     void GetPassabilityClasses(std::map<std::string, pass_class_t>& passClasses) const override;
     172             :     void GetPassabilityClasses(
     173             :         std::map<std::string, pass_class_t>& nonPathfindingPassClasses,
     174             :         std::map<std::string, pass_class_t>& pathfindingPassClasses) const override;
     175             : 
     176             :     const PathfinderPassability* GetPassabilityFromMask(pass_class_t passClass) const;
     177             : 
     178         189 :     entity_pos_t GetClearance(pass_class_t passClass) const override
     179             :     {
     180         189 :         const PathfinderPassability* passability = GetPassabilityFromMask(passClass);
     181         189 :         if (!passability)
     182           0 :             return fixed::Zero();
     183             : 
     184         189 :         return passability->m_Clearance;
     185             :     }
     186             : 
     187           3 :     entity_pos_t GetMaximumClearance() const override
     188             :     {
     189           3 :         entity_pos_t max = fixed::Zero();
     190             : 
     191          30 :         for (const PathfinderPassability& passability : m_PassClasses)
     192          27 :             if (passability.m_Clearance > max)
     193             :                 max = passability.m_Clearance;
     194             : 
     195           3 :         return max + Pathfinding::CLEARANCE_EXTENSION_RADIUS;
     196             :     }
     197             : 
     198             :     const Grid<NavcellData>& GetPassabilityGrid() override;
     199             : 
     200           0 :     const GridUpdateInformation& GetAIPathfinderDirtinessInformation() const override
     201             :     {
     202           0 :         return m_AIPathfinderDirtinessInformation;
     203             :     }
     204             : 
     205           7 :     void FlushAIPathfinderDirtinessInformation() override
     206             :     {
     207           7 :         m_AIPathfinderDirtinessInformation.Clean();
     208           0 :     }
     209             : 
     210             :     Grid<std::uint16_t> ComputeShoreGrid(bool expandOnWater = false) override;
     211             : 
     212             :     void ComputePathImmediate(entity_pos_t x0, entity_pos_t z0, const PathGoal& goal, pass_class_t passClass, WaypointPath& ret) const override;
     213             : 
     214             :     std::uint32_t ComputePathAsync(entity_pos_t x0, entity_pos_t z0, const PathGoal& goal, pass_class_t passClass, entity_id_t notify) override;
     215             : 
     216             :     WaypointPath ComputeShortPathImmediate(const ShortPathRequest& request) const override;
     217             : 
     218             :     std::uint32_t ComputeShortPathAsync(entity_pos_t x0, entity_pos_t z0, entity_pos_t clearance, entity_pos_t range, const PathGoal& goal, pass_class_t passClass, bool avoidMovingUnits, entity_id_t controller, entity_id_t notify) override;
     219             : 
     220             :     bool IsGoalReachable(entity_pos_t x0, entity_pos_t z0, const PathGoal& goal, pass_class_t passClass) override;
     221             : 
     222             :     void SetDebugPath(entity_pos_t x0, entity_pos_t z0, const PathGoal& goal, pass_class_t passClass) override;
     223             : 
     224             :     void SetDebugOverlay(bool enabled) override;
     225             : 
     226             :     void SetHierDebugOverlay(bool enabled) override;
     227             : 
     228             :     void GetDebugData(std::uint32_t& steps, double& time, Grid<std::uint8_t>& grid) const override;
     229             : 
     230             :     void SetAtlasOverlay(bool enable, pass_class_t passClass = 0) override;
     231             : 
     232             :     std::vector<CFixedVector2D> DistributeAround(std::vector<entity_id_t> units, entity_pos_t x, entity_pos_t z) const override;
     233             : 
     234             :     bool CheckMovement(const IObstructionTestFilter& filter, entity_pos_t x0, entity_pos_t z0, entity_pos_t x1, entity_pos_t z1, entity_pos_t r, pass_class_t passClass) const override;
     235             : 
     236             :     ICmpObstruction::EFoundationCheck CheckUnitPlacement(const IObstructionTestFilter& filter, entity_pos_t x, entity_pos_t z, entity_pos_t r, pass_class_t passClass, bool onlyCenterPoint) const override;
     237             : 
     238             :     ICmpObstruction::EFoundationCheck CheckBuildingPlacement(const IObstructionTestFilter& filter, entity_pos_t x, entity_pos_t z, entity_pos_t a, entity_pos_t w, entity_pos_t h, entity_id_t id, pass_class_t passClass) const override;
     239             : 
     240             :     ICmpObstruction::EFoundationCheck CheckBuildingPlacement(const IObstructionTestFilter& filter, entity_pos_t x, entity_pos_t z, entity_pos_t a, entity_pos_t w, entity_pos_t h, entity_id_t id, pass_class_t passClass, bool onlyCenterPoint) const override;
     241             : 
     242             :     void SendRequestedPaths() override;
     243             : 
     244             :     void StartProcessingMoves(bool useMax) override;
     245             : 
     246             :     template <typename T>
     247             :     std::vector<T> GetMovesToProcess(std::vector<T>& requests, bool useMax = false, size_t maxMoves = 0);
     248             : 
     249             :     template <typename T>
     250             :     void PushRequestsToWorkers(std::vector<T>& from);
     251             : 
     252             :     /**
     253             :      * Regenerates the grid based on the current obstruction list, if necessary
     254             :      */
     255             :     void UpdateGrid() override;
     256             : 
     257             :     /**
     258             :      * Updates the terrain-only grid without updating the dirtiness informations.
     259             :      * Useful for fast passability updates in Atlas.
     260             :      */
     261             :     void MinimalTerrainUpdate(int itile0, int jtile0, int itile1, int jtile1);
     262             : 
     263             :     /**
     264             :      * Regenerates the terrain-only grid.
     265             :      * Atlas doesn't need to have passability cells expanded.
     266             :      */
     267             :     void TerrainUpdateHelper(bool expandPassability = true, int itile0 = -1, int jtile0 = -1, int itile1 = -1, int jtile1 = -1);
     268             : 
     269             :     void RenderSubmit(SceneCollector& collector);
     270             : };
     271             : #endif // INCLUDED_CCMPPATHFINDER_COMMON

Generated by: LCOV version 1.16