LCOV - code coverage report
Current view: top level - source/simulation2/helpers - HierarchicalPathfinder.h (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 39 46 84.8 %
Date: 2026-12-03 01:19:39 Functions: 4 5 80.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_HIERPATHFINDER
      19             : #define INCLUDED_HIERPATHFINDER
      20             : 
      21             : #include "Pathfinding.h"
      22             : 
      23             : #include "graphics/SColor.h"
      24             : #include "lib/code_annotation.h"
      25             : #include "lib/debug.h"
      26             : #include "ps/CLogger.h"
      27             : #include "renderer/TerrainOverlay.h"
      28             : 
      29             : #include <cstddef>
      30             : #include <limits>
      31             : #include <map>
      32             : #include <set>
      33             : #include <string>
      34             : #include <utility>
      35             : #include <vector>
      36             : 
      37             : class CSimContext;
      38             : class PathGoal;
      39             : struct SOverlayLine;
      40             : template <typename T> class Grid;
      41             : 
      42             : /**
      43             :  * Hierarchical pathfinder.
      44             :  *
      45             :  * Deals with connectivity (can point A reach point B?).
      46             :  *
      47             :  * The navcell-grid representation of the map is split into fixed-size chunks.
      48             :  * Within a chunk, each maximal set of adjacently-connected passable navcells
      49             :  * is defined as a region.
      50             :  * Each region is a vertex in the hierarchical pathfinder's graph.
      51             :  * When two regions in adjacent chunks are connected by passable navcells,
      52             :  * the graph contains an edge between the corresponding two vertexes.
      53             :  * By design, there can never be an edge between two regions in the same chunk.
      54             :  *
      55             :  * Those fixed-size chunks are used to efficiently compute "global regions" by effectively flood-filling.
      56             :  * Those can then be used to immediately determine if two reachables points are connected.
      57             :  *
      58             :  * The main use of this class is to convert an arbitrary PathGoal to a reachable navcell.
      59             :  * This happens in MakeGoalReachable.
      60             :  *
      61             :  */
      62             : 
      63             : #ifdef TEST
      64             : class TestCmpPathfinder;
      65             : class TestHierarchicalPathfinder;
      66             : #endif
      67             : 
      68             : class SceneCollector;
      69             : 
      70             : class HierarchicalPathfinder
      71             : {
      72             : #ifdef TEST
      73             :     friend class TestCmpPathfinder;
      74             :     friend class TestHierarchicalPathfinder;
      75             : #endif
      76             : public:
      77             :     typedef std::uint32_t GlobalRegionID;
      78             : 
      79             :     struct RegionID
      80             :     {
      81             :         std::uint8_t ci, cj; // chunk ID
      82             :         std::uint16_t r; // unique-per-chunk local region ID
      83             : 
      84       13628 :         RegionID(std::uint8_t ci, std::uint8_t cj, std::uint16_t r) : ci(ci), cj(cj), r(r) { }
      85             : 
      86     1391005 :         bool operator<(const RegionID& b) const
      87             :         {
      88             :             // Sort by chunk ID, then by per-chunk region ID
      89     1391005 :             if (ci < b.ci)
      90             :                 return true;
      91     1196029 :             if (b.ci < ci)
      92             :                 return false;
      93      962355 :             if (cj < b.cj)
      94             :                 return true;
      95      736246 :             if (b.cj < cj)
      96             :                 return false;
      97      582435 :             return r < b.r;
      98             :         }
      99             : 
     100      951288 :         bool operator==(const RegionID& b) const
     101             :         {
     102      478232 :             return ((ci == b.ci) && (cj == b.cj) && (r == b.r));
     103             :         }
     104             : 
     105             :         // Returns the distance from the center to the point (i, j)
     106      337386 :         inline std::uint32_t DistanceTo(std::uint16_t i, std::uint16_t j) const
     107             :         {
     108      337386 :             return (ci * CHUNK_SIZE + CHUNK_SIZE/2 - i) * (ci * CHUNK_SIZE + CHUNK_SIZE/2 - i) +
     109        1344 :                    (cj * CHUNK_SIZE + CHUNK_SIZE/2 - j) * (cj * CHUNK_SIZE + CHUNK_SIZE/2 - j);
     110             :         }
     111             : 
     112             :     };
     113             : 
     114             :     HierarchicalPathfinder();
     115             :     ~HierarchicalPathfinder();
     116             : 
     117             :     void SetDebugOverlay(bool enabled, const CSimContext* simContext);
     118             : 
     119             :     // Non-pathfinding grids will never be recomputed on calling HierarchicalPathfinder::Update
     120             :     void Recompute(Grid<NavcellData>* passabilityGrid,
     121             :         const std::map<std::string, pass_class_t>& nonPathfindingPassClassMasks,
     122             :         const std::map<std::string, pass_class_t>& pathfindingPassClassMasks);
     123             : 
     124             :     void Update(Grid<NavcellData>* grid, const Grid<std::uint8_t>& dirtinessGrid);
     125             : 
     126             :     RegionID Get(std::uint16_t i, std::uint16_t j, pass_class_t passClass) const;
     127             : 
     128             :     GlobalRegionID GetGlobalRegion(std::uint16_t i, std::uint16_t j, pass_class_t passClass) const;
     129             :     GlobalRegionID GetGlobalRegion(RegionID region, pass_class_t passClass) const;
     130             : 
     131             :     /**
     132             :      * Updates @p goal so that it's guaranteed to be reachable from the navcell
     133             :      * @p i0, @p j0 (which is assumed to be on a passable navcell).
     134             :      *
     135             :      * If the goal is not reachable, it is replaced with a point goal nearest to
     136             :      * the goal center.
     137             :      *
     138             :      * In the case of a non-point reachable goal, it is replaced with a point goal
     139             :      * at the reachable navcell of the goal which is nearest to the starting navcell.
     140             :      *
     141             :      * @returns true if the goal was reachable, false otherwise.
     142             :      */
     143             :     bool MakeGoalReachable(std::uint16_t i0, std::uint16_t j0, PathGoal& goal,
     144             :         pass_class_t passClass) const;
     145             : 
     146             :     /**
     147             :      * @return true if the goal is reachable from navcell i0, j0.
     148             :      * (similar to MakeGoalReachable but only checking for reachability).
     149             :      */
     150             :     bool IsGoalReachable(std::uint16_t i0, std::uint16_t j0, const PathGoal& goal,
     151             :         pass_class_t passClass) const;
     152             : 
     153             :     /**
     154             :      * Updates @p i, @p j (which is assumed to be an impassable navcell)
     155             :      * to the nearest passable navcell.
     156             :      */
     157             :     void FindNearestPassableNavcell(std::uint16_t& i, std::uint16_t& j, pass_class_t passClass) const;
     158             : 
     159             :     /**
     160             :      * Generates the connectivity grid associated with the given pass_class
     161             :      */
     162             :     Grid<std::uint16_t> GetConnectivityGrid(pass_class_t passClass) const;
     163             : 
     164           0 :     pass_class_t GetPassabilityClass(const std::string& name) const
     165             :     {
     166           0 :         auto it = m_PassClassMasks.find(name);
     167           0 :         if (it != m_PassClassMasks.end())
     168           0 :             return it->second;
     169             : 
     170           0 :         LOGERROR("Invalid passability class name '{}'", name);
     171           0 :         return 0;
     172             :     }
     173             : 
     174             :     void RenderSubmit(SceneCollector& collector);
     175             : 
     176             : private:
     177             :     static const std::uint8_t CHUNK_SIZE = 96; // number of navcells per side
     178             :                                      // TODO: figure out best number. Probably 64 < n < 128
     179             : 
     180       13401 :     struct Chunk
     181             :     {
     182             :         std::uint8_t m_ChunkI, m_ChunkJ; // chunk ID
     183             :         std::vector<std::uint16_t> m_RegionsID; // IDs of local regions, 0 (impassable) excluded
     184             :         std::uint16_t m_Regions[CHUNK_SIZE][CHUNK_SIZE]; // local region ID per navcell
     185             : 
     186             :         cassert(CHUNK_SIZE*CHUNK_SIZE/2 < 65536); // otherwise we could overflow m_RegionsID with a checkerboard pattern
     187             : 
     188             :         void InitRegions(int ci, int cj, Grid<NavcellData>* grid, pass_class_t passClass);
     189             : 
     190             :         RegionID Get(int i, int j) const;
     191             : 
     192             :         void RegionCenter(std::uint16_t r, int& i, int& j) const;
     193             : 
     194             :         void RegionNavcellNearest(std::uint16_t r, int iGoal, int jGoal, int& iBest, int& jBest,
     195             :             std::uint32_t& dist2Best) const;
     196             : 
     197             :         bool RegionNearestNavcellInGoal(std::uint16_t r, std::uint16_t i0, std::uint16_t j0,
     198             :             const PathGoal& goal, std::uint16_t& iOut, std::uint16_t& jOut,
     199             :             std::uint32_t& dist2Best) const;
     200             : 
     201             : #ifdef TEST
     202             :         bool operator==(const Chunk& b) const
     203             :         {
     204             :             return (m_ChunkI == b.m_ChunkI && m_ChunkJ == b.m_ChunkJ &&
     205             :                 m_RegionsID.size() == b.m_RegionsID.size() && memcmp(&m_Regions, &b.m_Regions,
     206             :                 sizeof(std::uint16_t) * CHUNK_SIZE * CHUNK_SIZE) == 0);
     207             :         }
     208             : #endif
     209             :     };
     210             : 
     211        7648 :     const Chunk& GetChunk(std::uint8_t ci, std::uint8_t cj, pass_class_t passClass) const
     212             :     {
     213        7648 :         return m_Chunks.at(passClass).at(cj * m_ChunksW + ci);
     214             :     }
     215             : 
     216             :     typedef std::map<RegionID, std::set<RegionID> > EdgesMap;
     217             : 
     218             :     void ComputeNeighbors(EdgesMap& edges, Chunk& a, Chunk& b, bool transpose, bool opposite) const;
     219             :     void RecomputeAllEdges(pass_class_t passClass, EdgesMap& edges);
     220             :     void UpdateEdges(std::uint8_t ci, std::uint8_t cj, pass_class_t passClass, EdgesMap& edges);
     221             : 
     222             :     void UpdateGlobalRegions(const std::map<pass_class_t, std::vector<RegionID> >& needNewGlobalRegionMap);
     223             : 
     224             :     /**
     225             :      * Returns all reachable regions, optionally ordered in a specific manner.
     226             :      */
     227             :     template<typename Ordering>
     228         346 :     void FindReachableRegions(RegionID from, std::set<RegionID, Ordering>& reachable, pass_class_t passClass) const
     229             :     {
     230             :         // Flood-fill the region graph, starting at 'from',
     231             :         // collecting all the regions that are reachable via edges
     232         346 :         reachable.insert(from);
     233             : 
     234         346 :         const EdgesMap& edgeMap = m_Edges.at(passClass);
     235         346 :         if (edgeMap.find(from) == edgeMap.end())
     236           2 :             return;
     237             : 
     238         344 :         std::vector<RegionID> open;
     239         344 :         open.reserve(64);
     240         343 :         open.push_back(from);
     241             : 
     242       20292 :         while (!open.empty())
     243             :         {
     244       19948 :             RegionID curr = open.back();
     245       19948 :             open.pop_back();
     246             : 
     247       85800 :             for (const RegionID& region : edgeMap.at(curr))
     248             :                 // Add to the reachable set; if this is the first time we added
     249             :                 // it then also add it to the open list
     250       65854 :                 if (reachable.insert(region).second)
     251       19772 :                     open.push_back(region);
     252             :         }
     253         344 :     }
     254             : 
     255             :     struct SortByCenterToPoint
     256             :     {
     257         291 :         SortByCenterToPoint(std::uint16_t i, std::uint16_t j): gi(i), gj(j) {};
     258      336042 :         bool operator()(const HierarchicalPathfinder::RegionID& a, const HierarchicalPathfinder::RegionID& b) const
     259             :         {
     260      336042 :             if (a.DistanceTo(gi, gj) < b.DistanceTo(gi, gj))
     261             :                 return true;
     262      170633 :             if (a.DistanceTo(gi, gj) > b.DistanceTo(gi, gj))
     263             :                 return false;
     264       68690 :             return a.r < b.r;
     265             :         }
     266             :         std::uint16_t gi, gj;
     267             :     };
     268             : 
     269             :     void FindNearestNavcellInRegions(const std::set<RegionID, SortByCenterToPoint>& regions,
     270             :         std::uint16_t& iGoal, std::uint16_t& jGoal, pass_class_t passClass) const;
     271             : 
     272             :     struct InterestingRegion {
     273             :         RegionID region;
     274             :         std::uint16_t bestI;
     275             :         std::uint16_t bestJ;
     276             :     };
     277             : 
     278             :     struct SortByBestToPoint
     279             :     {
     280         965 :         SortByBestToPoint(std::uint16_t i, std::uint16_t j): gi(i), gj(j) {};
     281        1419 :         bool operator()(const InterestingRegion& a, const InterestingRegion& b) const
     282             :         {
     283        1419 :             if ((a.bestI - gi) * (a.bestI - gi) + (a.bestJ - gj) * (a.bestJ - gj) < (b.bestI - gi) * (b.bestI - gi) + (b.bestJ - gj) * (b.bestJ - gj))
     284             :                 return true;
     285         768 :             if ((a.bestI - gi) * (a.bestI - gi) + (a.bestJ - gj) * (a.bestJ - gj) > (b.bestI - gi) * (b.bestI - gi) + (b.bestJ - gj) * (b.bestJ - gj))
     286             :                 return false;
     287           0 :             return a.region.r < b.region.r;
     288             :         }
     289             :         std::uint16_t gi, gj;
     290             :     };
     291             : 
     292             :     // Returns the region along with the best cell for optimisation.
     293             :     void FindGoalRegionsAndBestNavcells(std::uint16_t i0, std::uint16_t j0, std::uint16_t gi,
     294             :         std::uint16_t gj, const PathGoal& goal, std::set<InterestingRegion,
     295             :         SortByBestToPoint>& regions, pass_class_t passClass) const;
     296             : 
     297             :     void FillRegionOnGrid(const RegionID& region, pass_class_t passClass, std::uint16_t value,
     298             :         Grid<std::uint16_t>& grid) const;
     299             : 
     300             :     std::uint16_t m_W, m_H;
     301             :     std::uint8_t m_ChunksW, m_ChunksH;
     302             :     std::map<pass_class_t, std::vector<Chunk> > m_Chunks;
     303             : 
     304             :     std::map<pass_class_t, EdgesMap> m_Edges;
     305             : 
     306             :     std::map<pass_class_t, std::map<RegionID, GlobalRegionID> > m_GlobalRegions;
     307             :     GlobalRegionID m_NextGlobalRegionID;
     308             : 
     309             :     // Passability classes for which grids will be updated when calling Update
     310             :     std::map<std::string, pass_class_t> m_PassClassMasks;
     311             : 
     312             :     void AddDebugEdges(pass_class_t passClass);
     313             :     TerrainTextureOverlay* m_DebugOverlay;
     314             :     const CSimContext* m_SimContext; // Used for drawing the debug lines
     315             : 
     316             : public:
     317             :     std::vector<SOverlayLine> m_DebugOverlayLines;
     318             : };
     319             : #endif // INCLUDED_HIERPATHFINDER

Generated by: LCOV version 1.16