LCOV - code coverage report
Current view: top level - source/simulation2/components - CCmpPathfinder.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 329 511 64.4 %
Date: 2026-12-02 01:21:50 Functions: 25 47 53.2 %

          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             : /**
      19             :  * @file
      20             :  * Common code and setup code for CCmpPathfinder.
      21             :  */
      22             : 
      23             : #include "precompiled.h"
      24             : 
      25             : #include "CCmpPathfinder_Common.h"
      26             : 
      27             : #include "graphics/Terrain.h"
      28             : #include "lib/code_generation.h"
      29             : #include "lib/debug.h"
      30             : #include "lib/path.h"
      31             : #include "maths/Fixed.h"
      32             : #include "maths/FixedVector2D.h"
      33             : #include "maths/MathUtil.h"
      34             : #include "ps/CLogger.h"
      35             : #include "ps/Filesystem.h"
      36             : #include "ps/Future.h"
      37             : #include "ps/Profile.h"
      38             : #include "ps/Profiler2.h"
      39             : #include "ps/TaskManager.h"
      40             : #include "ps/XML/Xeromyces.h"
      41             : #include "simulation2/MessageTypes.h"
      42             : #include "simulation2/components/ICmpObstruction.h"
      43             : #include "simulation2/components/ICmpObstructionManager.h"
      44             : #include "simulation2/components/ICmpPathfinder.h"
      45             : #include "simulation2/components/ICmpPosition.h"
      46             : #include "simulation2/components/ICmpTerrain.h"
      47             : #include "simulation2/components/ICmpWaterManager.h"
      48             : #include "simulation2/helpers/Grid.h"
      49             : #include "simulation2/helpers/HierarchicalPathfinder.h"
      50             : #include "simulation2/helpers/LongPathfinder.h"
      51             : #include "simulation2/helpers/MapEdgeTiles.h"
      52             : #include "simulation2/helpers/PathGoal.h"
      53             : #include "simulation2/helpers/Pathfinding.h"
      54             : #include "simulation2/helpers/Position.h"
      55             : #include "simulation2/helpers/Rasterize.h"
      56             : #include "simulation2/helpers/VertexPathfinder.h"
      57             : #include "simulation2/serialization/SerializeTemplates.h"
      58             : #include "simulation2/serialization/SerializedPathfinder.h"
      59             : #include "simulation2/serialization/SerializedTypes.h"
      60             : #include "simulation2/system/Component.h"
      61             : #include "simulation2/system/Entity.h"
      62             : #include "simulation2/system/Message.h"
      63             : 
      64             : #include <algorithm>
      65             : #include <atomic>
      66             : #include <cstring>
      67             : #include <map>
      68             : #include <memory>
      69             : #include <string>
      70             : #include <type_traits>
      71             : #include <utility>
      72             : #include <vector>
      73             : 
      74             : class SceneCollector;
      75             : 
      76         274 : REGISTER_COMPONENT_TYPE(Pathfinder)
      77             : 
      78             : namespace
      79             : {
      80           0 : void BuildTextureRGBA(const CCmpPathfinder& pathfinder, std::uint8_t* data, std::size_t w, std::size_t h)
      81             : {
      82             :     // Render navcell passability, based on the terrain-only grid
      83           0 :     TerrainTextureOverlay::OverwriteEachTile(data, w, h, [&](const int i, const int j)
      84             :     {
      85           0 :         if (!IS_PASSABLE(pathfinder.m_TerrainOnlyGrid->get(j, i),
      86             :             pathfinder.m_OverlayPassClass))
      87             :         {
      88           0 :             return SColor4ub{255, 0, 0, 127};
      89             :         }
      90           0 :         return SColor4ub{0, 0, 0, 0};
      91             :     });
      92           0 : }
      93             : }
      94             : 
      95           7 : void CCmpPathfinder::Init(const CParamNode&)
      96             : {
      97           7 :     m_GridSize = 0;
      98           7 :     m_Grid = NULL;
      99           7 :     m_TerrainOnlyGrid = NULL;
     100             : 
     101           7 :     FlushAIPathfinderDirtinessInformation();
     102             : 
     103           7 :     m_NextAsyncTicket = 1;
     104             : 
     105           7 :     m_AtlasOverlay = NULL;
     106             : 
     107           7 :     size_t workerThreads = g_TaskManager.GetNumberOfWorkers();
     108             :     // Store one vertex pathfinder for each thread (including the main thread).
     109          35 :     while (m_VertexPathfinders.size() < workerThreads + 1)
     110          28 :         m_VertexPathfinders.emplace_back(m_GridSize, m_TerrainOnlyGrid);
     111           7 :     m_LongPathfinder = std::make_unique<LongPathfinder>();
     112           7 :     m_PathfinderHier = std::make_unique<HierarchicalPathfinder>();
     113             : 
     114             :     // Set up one future for each worker thread.
     115           7 :     m_Futures.resize(workerThreads);
     116             : 
     117             :     // Register Relax NG validator
     118          14 :     g_Xeromyces.AddValidator(g_VFS, "pathfinder", "simulation/data/pathfinder.rng");
     119             : 
     120             :     // Since this is used as a system component (not loaded from an entity template),
     121             :     // we can't use the real paramNode (it won't get handled properly when deserializing),
     122             :     // so load the data from a special XML file.
     123           7 :     CParamNode externalParamNode;
     124          14 :     CParamNode::LoadXML(externalParamNode, L"simulation/data/pathfinder.xml", "pathfinder");
     125             : 
     126             :     // Paths are computed:
     127             :     //  - Before MT_Update
     128             :     //  - Before MT_MotionUnitFormation
     129             :     //  -  asynchronously between turn end and turn start.
     130             :     // The latter of these must compute all outstanding requests, but the former two are capped
     131             :     // to avoid spending too much time there (since the latter are threaded and thus much 'cheaper').
     132             :     // This loads that maximum number (note that it's per computation call, not per turn for now).
     133           7 :     const CParamNode pathingSettings = externalParamNode.GetChild("Pathfinder");
     134          14 :     m_MaxSameTurnMoves = static_cast<std::uint16_t>(
     135           7 :         pathingSettings.GetChild("MaxSameTurnMoves").ToInt());
     136             : 
     137           7 :     const CParamNode::ChildrenMap& passClasses = externalParamNode.GetChild("Pathfinder").GetChild("PassabilityClasses").GetChildren();
     138          58 :     for (CParamNode::ChildrenMap::const_iterator it = passClasses.begin(); it != passClasses.end(); ++it)
     139             :     {
     140          51 :         std::string name = it->first;
     141          51 :         ENSURE((int)m_PassClasses.size() <= PASS_CLASS_BITS);
     142          51 :         pass_class_t mask = PASS_CLASS_MASK_FROM_INDEX(m_PassClasses.size());
     143          51 :         m_PassClasses.push_back(PathfinderPassability(mask, it->second));
     144          51 :         m_PassClassMasks[name] = mask;
     145          51 :     }
     146           7 : }
     147             : 
     148          27 : CCmpPathfinder::~CCmpPathfinder() {};
     149             : 
     150           7 : void CCmpPathfinder::Deinit()
     151             : {
     152           7 :     SetDebugOverlay(false); // cleans up memory
     153             : 
     154           7 :     m_Futures.clear();
     155             : 
     156           7 :     SAFE_DELETE(m_AtlasOverlay);
     157             : 
     158          10 :     SAFE_DELETE(m_Grid);
     159          10 :     SAFE_DELETE(m_TerrainOnlyGrid);
     160           7 : }
     161             : 
     162             : template<>
     163             : struct SerializeHelper<LongPathRequest>
     164             : {
     165             :     template<typename S>
     166          84 :     void operator()(S& serialize, const char* /*name*/, Serialize::qualify<S, LongPathRequest> value)
     167             :     {
     168          84 :         serialize.NumberU32_Unbounded("ticket", value.ticket);
     169          84 :         serialize.NumberFixed_Unbounded("x0", value.x0);
     170          84 :         serialize.NumberFixed_Unbounded("z0", value.z0);
     171          84 :         Serializer(serialize, "goal", value.goal);
     172          84 :         serialize.NumberU16_Unbounded("pass class", value.passClass);
     173          84 :         serialize.NumberU32_Unbounded("notify", value.notify);
     174          84 :     }
     175             : };
     176             : 
     177             : template<>
     178             : struct SerializeHelper<ShortPathRequest>
     179             : {
     180             :     template<typename S>
     181           0 :     void operator()(S& serialize, const char* /*name*/, Serialize::qualify<S, ShortPathRequest> value)
     182             :     {
     183           0 :         serialize.NumberU32_Unbounded("ticket", value.ticket);
     184           0 :         serialize.NumberFixed_Unbounded("x0", value.x0);
     185           0 :         serialize.NumberFixed_Unbounded("z0", value.z0);
     186           0 :         serialize.NumberFixed_Unbounded("clearance", value.clearance);
     187           0 :         serialize.NumberFixed_Unbounded("range", value.range);
     188           0 :         Serializer(serialize, "goal", value.goal);
     189           0 :         serialize.NumberU16_Unbounded("pass class", value.passClass);
     190           0 :         serialize.Bool("avoid moving units", value.avoidMovingUnits);
     191           0 :         serialize.NumberU32_Unbounded("group", value.group);
     192           0 :         serialize.NumberU32_Unbounded("notify", value.notify);
     193           0 :     }
     194             : };
     195             : 
     196             : template<typename S>
     197          18 : void CCmpPathfinder::SerializeCommon(S& serialize)
     198             : {
     199          18 :     Serializer(serialize, "long requests", m_LongPathRequests.m_Requests);
     200          18 :     Serializer(serialize, "short requests", m_ShortPathRequests.m_Requests);
     201          18 :     serialize.NumberU32_Unbounded("next ticket", m_NextAsyncTicket);
     202          18 :     serialize.NumberU16_Unbounded("grid size", m_GridSize);
     203          18 : }
     204             : 
     205          18 : void CCmpPathfinder::Serialize(ISerializer& serialize)
     206             : {
     207          18 :     SerializeCommon(serialize);
     208          18 : }
     209             : 
     210           0 : void CCmpPathfinder::Deserialize(const CParamNode& paramNode, IDeserializer& deserialize)
     211             : {
     212           0 :     Init(paramNode);
     213             : 
     214           0 :     SerializeCommon(deserialize);
     215           0 : }
     216             : 
     217           9 : void CCmpPathfinder::HandleMessage(const CMessage& msg, bool /*global*/)
     218             : {
     219           9 :     switch (msg.GetType())
     220             :     {
     221           0 :     case MT_RenderSubmit:
     222           0 :     {
     223           0 :         const CMessageRenderSubmit& msgData = static_cast<const CMessageRenderSubmit&> (msg);
     224           9 :         RenderSubmit(msgData.collector);
     225             :         break;
     226             :     }
     227           3 :     case MT_TerrainChanged:
     228           3 :     {
     229           3 :         const CMessageTerrainChanged& msgData = static_cast<const CMessageTerrainChanged&>(msg);
     230           3 :         m_TerrainDirty = true;
     231          12 :         MinimalTerrainUpdate(msgData.i0, msgData.j0, msgData.i1, msgData.j1);
     232             :         break;
     233             :     }
     234           6 :     case MT_WaterChanged:
     235           6 :     case MT_ObstructionMapShapeChanged:
     236           6 :         m_TerrainDirty = true;
     237           6 :         UpdateGrid();
     238           6 :         break;
     239           0 :     case MT_Deserialized:
     240           0 :         UpdateGrid();
     241             :         // In case we were serialised with requests pending, we need to process them.
     242           0 :         if (!m_ShortPathRequests.m_Requests.empty() || !m_LongPathRequests.m_Requests.empty())
     243             :         {
     244           0 :             ENSURE(CmpPtr<ICmpObstructionManager>(GetSystemEntity()));
     245           0 :             StartProcessingMoves(false);
     246             :         }
     247             :         break;
     248             :     }
     249           9 : }
     250             : 
     251           0 : void CCmpPathfinder::RenderSubmit(SceneCollector& collector)
     252             : {
     253           0 :     g_VertexPathfinderDebugOverlay.RenderSubmit(collector);
     254           0 :     m_PathfinderHier->RenderSubmit(collector);
     255           0 : }
     256             : 
     257         954 : void CCmpPathfinder::SetDebugPath(entity_pos_t x0, entity_pos_t z0, const PathGoal& goal, pass_class_t passClass)
     258             : {
     259         954 :     m_LongPathfinder->SetDebugPath(*m_PathfinderHier, x0, z0, goal, passClass);
     260         954 : }
     261             : 
     262           7 : void CCmpPathfinder::SetDebugOverlay(bool enabled)
     263             : {
     264           7 :     g_VertexPathfinderDebugOverlay.SetDebugOverlay(enabled);
     265           7 :     m_LongPathfinder->SetDebugOverlay(enabled);
     266           7 : }
     267             : 
     268           0 : void CCmpPathfinder::SetHierDebugOverlay(bool enabled)
     269             : {
     270           0 :     m_PathfinderHier->SetDebugOverlay(enabled, &GetSimContext());
     271           0 : }
     272             : 
     273           0 : void CCmpPathfinder::GetDebugData(std::uint32_t& steps, double& time, Grid<std::uint8_t>& grid) const
     274             : {
     275           0 :     m_LongPathfinder->GetDebugData(steps, time, grid);
     276           0 : }
     277             : 
     278           0 : void CCmpPathfinder::SetAtlasOverlay(bool enable, pass_class_t passClass)
     279             : {
     280           0 :     if (enable)
     281             :     {
     282           0 :         m_OverlayPassClass = passClass;
     283           0 :         if (!m_AtlasOverlay)
     284             :         {
     285           0 :             m_AtlasOverlay = new TerrainTextureOverlay{Pathfinding::NAVCELLS_PER_TERRAIN_TILE,
     286           0 :                 std::bind_front(BuildTextureRGBA, std::ref(*this))};
     287             :         }
     288             :     }
     289             :     else
     290           0 :         SAFE_DELETE(m_AtlasOverlay);
     291           0 : }
     292             : 
     293         195 : pass_class_t CCmpPathfinder::GetPassabilityClass(const std::string& name) const
     294             : {
     295         195 :     std::map<std::string, pass_class_t>::const_iterator it = m_PassClassMasks.find(name);
     296         195 :     if (it == m_PassClassMasks.end())
     297             :     {
     298           0 :         LOGERROR("Invalid passability class name '{}'", name);
     299           0 :         return 0;
     300             :     }
     301             : 
     302         195 :     return it->second;
     303             : }
     304             : 
     305           3 : void CCmpPathfinder::GetPassabilityClasses(std::map<std::string, pass_class_t>& passClasses) const
     306             : {
     307           3 :     passClasses = m_PassClassMasks;
     308           3 : }
     309             : 
     310           9 : void CCmpPathfinder::GetPassabilityClasses(std::map<std::string, pass_class_t>& nonPathfindingPassClasses, std::map<std::string, pass_class_t>& pathfindingPassClasses) const
     311             : {
     312          90 :     for (const std::pair<const std::string, pass_class_t>& pair : m_PassClassMasks)
     313             :     {
     314          81 :         if ((GetPassabilityFromMask(pair.second)->m_Obstructions == PathfinderPassability::PATHFINDING))
     315          36 :             pathfindingPassClasses[pair.first] = pair.second;
     316             :         else
     317          45 :             nonPathfindingPassClasses[pair.first] = pair.second;
     318             :     }
     319           9 : }
     320             : 
     321         270 : const PathfinderPassability* CCmpPathfinder::GetPassabilityFromMask(pass_class_t passClass) const
     322             : {
     323         984 :     for (const PathfinderPassability& passability : m_PassClasses)
     324             :     {
     325         984 :         if (passability.m_Mask == passClass)
     326           0 :             return &passability;
     327             :     }
     328             : 
     329             :     return NULL;
     330             : }
     331             : 
     332           6 : const Grid<NavcellData>& CCmpPathfinder::GetPassabilityGrid()
     333             : {
     334           6 :     if (!m_Grid)
     335           0 :         UpdateGrid();
     336             : 
     337           6 :     return *m_Grid;
     338             : }
     339             : 
     340             : /**
     341             :  * Given a grid of passable/impassable navcells (based on some passability mask),
     342             :  * computes a new grid where a navcell is impassable (per that mask) if
     343             :  * it is <=clearance navcells away from an impassable navcell in the original grid.
     344             :  * The results are ORed onto the original grid.
     345             :  *
     346             :  * This is used for adding clearance onto terrain-based navcell passability.
     347             :  *
     348             :  * TODO PATHFINDER: might be nicer to get rounded corners by measuring clearances as
     349             :  * Euclidean distances; currently it effectively does dist=max(dx,dy) instead.
     350             :  * This would only really be a problem for big clearances.
     351             :  */
     352          24 : static void ExpandImpassableCells(Grid<NavcellData>& grid, std::uint16_t clearance, pass_class_t mask)
     353             : {
     354          24 :     PROFILE3("ExpandImpassableCells");
     355             : 
     356          24 :     std::uint16_t w = grid.m_W;
     357          24 :     std::uint16_t h = grid.m_H;
     358             : 
     359             :     // First expand impassable cells horizontally into a temporary 1-bit grid
     360          24 :     Grid<std::uint8_t> tempGrid(w, h);
     361       18456 :     for (std::uint16_t j = 0; j < h; ++j)
     362             :     {
     363             :         // New cell (i,j) is blocked if (i',j) blocked for any i-clearance <= i' <= i+clearance
     364             : 
     365             :         // Count the number of blocked cells around i=0
     366             :         std::uint16_t numBlocked = 0;
     367      115200 :         for (std::uint16_t i = 0; i <= clearance && i < w; ++i)
     368       96768 :             if (!IS_PASSABLE(grid.get(i, j), mask))
     369       96768 :                 ++numBlocked;
     370             : 
     371    14174208 :         for (std::uint16_t i = 0; i < w; ++i)
     372             :         {
     373             :             // Store a flag if blocked by at least one nearby cell
     374    14155776 :             if (numBlocked)
     375     7531236 :                 tempGrid.set(i, j, 1);
     376             : 
     377             :             // Slide the numBlocked window along:
     378             :             // remove the old i-clearance value, add the new (i+1)+clearance
     379             :             // (avoiding overflowing the grid)
     380    14155776 :             if (i >= clearance && !IS_PASSABLE(grid.get(i-clearance, j), mask))
     381     7417140 :                 --numBlocked;
     382    14155776 :             if (i+1+clearance < w && !IS_PASSABLE(grid.get(i+1+clearance, j), mask))
     383     7398708 :                 ++numBlocked;
     384             :         }
     385             :     }
     386             : 
     387       18456 :     for (std::uint16_t i = 0; i < w; ++i)
     388             :     {
     389             :         // New cell (i,j) is blocked if (i,j') blocked for any j-clearance <= j' <= j+clearance
     390             :         // Count the number of blocked cells around j=0
     391             :         std::uint16_t numBlocked = 0;
     392      115200 :         for (std::uint16_t j = 0; j <= clearance && j < h; ++j)
     393       96768 :             if (tempGrid.get(i, j))
     394       96768 :                 ++numBlocked;
     395             : 
     396    14174208 :         for (std::uint16_t j = 0; j < h; ++j)
     397             :         {
     398             :             // Add the mask if blocked by at least one nearby cell
     399    14155776 :             if (numBlocked)
     400     7566756 :                 grid.set(i, j, grid.get(i, j) | mask);
     401             : 
     402             :             // Slide the numBlocked window along:
     403             :             // remove the old j-clearance value, add the new (j+1)+clearance
     404             :             // (avoiding overflowing the grid)
     405    14155776 :             if (j >= clearance && tempGrid.get(i, j-clearance))
     406     7452900 :                 --numBlocked;
     407    14155776 :             if (j+1+clearance < h && tempGrid.get(i, j+1+clearance))
     408     7434468 :                 ++numBlocked;
     409             :         }
     410             :     }
     411          24 : }
     412             : 
     413           9 : Grid<std::uint16_t> CCmpPathfinder::ComputeShoreGrid(bool expandOnWater)
     414             : {
     415           9 :     PROFILE3("ComputeShoreGrid");
     416             : 
     417           9 :     CmpPtr<ICmpWaterManager> cmpWaterManager(GetSystemEntity());
     418             : 
     419             :     // TODO: these bits should come from ICmpTerrain
     420           9 :     CTerrain& terrain = GetSimContext().GetTerrain();
     421             : 
     422             :     // avoid integer overflow in intermediate calculation
     423           9 :     const std::uint16_t shoreMax = 32767;
     424             : 
     425           9 :     std::uint16_t shoreGridSize = terrain.GetTilesPerSide();
     426             : 
     427             :     // First pass - find underwater tiles
     428           9 :     Grid<std::uint8_t> waterGrid(shoreGridSize, shoreGridSize);
     429        1737 :     for (std::uint16_t j = 0; j < shoreGridSize; ++j)
     430             :     {
     431      333504 :         for (std::uint16_t i = 0; i < shoreGridSize; ++i)
     432             :         {
     433      331776 :             fixed x, z;
     434      331776 :             Pathfinding::TerrainTileCenter(i, j, x, z);
     435             : 
     436      331776 :             bool underWater = cmpWaterManager && (cmpWaterManager->GetWaterLevel(x, z) > terrain.GetExactGroundLevelFixed(x, z));
     437      331776 :             waterGrid.set(i, j, underWater ? 1 : 0);
     438             :         }
     439             :     }
     440             : 
     441             :     // Second pass - find shore tiles
     442           9 :     Grid<std::uint16_t> shoreGrid(shoreGridSize, shoreGridSize);
     443        1737 :     for (std::uint16_t j = 0; j < shoreGridSize; ++j)
     444             :     {
     445      333504 :         for (std::uint16_t i = 0; i < shoreGridSize; ++i)
     446             :         {
     447             :             // Find a land tile
     448      331776 :             if (!waterGrid.get(i, j))
     449             :             {
     450             :                 // If it's bordered by water, it's a shore tile
     451      331776 :                 if ((i > 0 && waterGrid.get(i-1, j)) || (i > 0 && j < shoreGridSize-1 && waterGrid.get(i-1, j+1)) || (i > 0 && j > 0 && waterGrid.get(i-1, j-1))
     452      331776 :                     || (i < shoreGridSize-1 && waterGrid.get(i+1, j)) || (i < shoreGridSize-1 && j < shoreGridSize-1 && waterGrid.get(i+1, j+1)) || (i < shoreGridSize-1 && j > 0 && waterGrid.get(i+1, j-1))
     453      663552 :                     || (j > 0 && waterGrid.get(i, j-1)) || (j < shoreGridSize-1 && waterGrid.get(i, j+1))
     454             :                     )
     455           0 :                     shoreGrid.set(i, j, 0);
     456             :                 else
     457      331776 :                     shoreGrid.set(i, j, shoreMax);
     458             :             }
     459             :             // If we want to expand on water, we want water tiles not to be shore tiles
     460           0 :             else if (expandOnWater)
     461      331776 :                 shoreGrid.set(i, j, shoreMax);
     462             :         }
     463             :     }
     464             : 
     465             :     // Expand influences on land to find shore distance
     466        1737 :     for (std::uint16_t y = 0; y < shoreGridSize; ++y)
     467             :     {
     468             :         std::uint16_t min = shoreMax;
     469      333504 :         for (std::uint16_t x = 0; x < shoreGridSize; ++x)
     470             :         {
     471      331776 :             if (!waterGrid.get(x, y) || expandOnWater)
     472             :             {
     473      331776 :                 std::uint16_t g = shoreGrid.get(x, y);
     474      331776 :                 if (g > min)
     475           0 :                     shoreGrid.set(x, y, min);
     476      331776 :                 else if (g < min)
     477      331776 :                     min = g;
     478             : 
     479      331776 :                 ++min;
     480             :             }
     481             :         }
     482      333504 :         for (std::uint16_t x = shoreGridSize; x > 0; --x)
     483             :         {
     484      331776 :             if (!waterGrid.get(x-1, y) || expandOnWater)
     485             :             {
     486      331776 :                 std::uint16_t g = shoreGrid.get(x-1, y);
     487      331776 :                 if (g > min)
     488           0 :                     shoreGrid.set(x-1, y, min);
     489      331776 :                 else if (g < min)
     490      331776 :                     min = g;
     491             : 
     492      331776 :                 ++min;
     493             :             }
     494             :         }
     495             :     }
     496        1737 :     for (std::uint16_t x = 0; x < shoreGridSize; ++x)
     497             :     {
     498             :         std::uint16_t min = shoreMax;
     499      333504 :         for (std::uint16_t y = 0; y < shoreGridSize; ++y)
     500             :         {
     501      331776 :             if (!waterGrid.get(x, y) || expandOnWater)
     502             :             {
     503      331776 :                 std::uint16_t g = shoreGrid.get(x, y);
     504      331776 :                 if (g > min)
     505           0 :                     shoreGrid.set(x, y, min);
     506      331776 :                 else if (g < min)
     507      331776 :                     min = g;
     508             : 
     509      331776 :                 ++min;
     510             :             }
     511             :         }
     512      333504 :         for (std::uint16_t y = shoreGridSize; y > 0; --y)
     513             :         {
     514      331776 :             if (!waterGrid.get(x, y-1) || expandOnWater)
     515             :             {
     516      331776 :                 std::uint16_t g = shoreGrid.get(x, y-1);
     517      331776 :                 if (g > min)
     518           0 :                     shoreGrid.set(x, y-1, min);
     519      331776 :                 else if (g < min)
     520      331776 :                     min = g;
     521             : 
     522      331776 :                 ++min;
     523             :             }
     524             :         }
     525             :     }
     526             : 
     527          18 :     return shoreGrid;
     528           9 : }
     529             : 
     530         189 : void CCmpPathfinder::UpdateGrid()
     531             : {
     532         189 :     PROFILE3("UpdateGrid");
     533             : 
     534         189 :     CmpPtr<ICmpTerrain> cmpTerrain(GetSimContext(), SYSTEM_ENTITY);
     535         189 :     if (!cmpTerrain)
     536             :         return; // error
     537             : 
     538         189 :     std::uint16_t gridSize = cmpTerrain->GetMapSize() / Pathfinding::NAVCELL_SIZE_INT;
     539         189 :     if (gridSize == 0)
     540             :         return;
     541             : 
     542             :     // If the terrain was resized then delete the old grid data
     543         189 :     if (m_Grid && m_GridSize != gridSize)
     544             :     {
     545           0 :         SAFE_DELETE(m_Grid);
     546           0 :         SAFE_DELETE(m_TerrainOnlyGrid);
     547             :     }
     548             : 
     549             :     // Initialise the terrain data when first needed
     550         189 :     if (!m_Grid)
     551             :     {
     552           3 :         m_GridSize = gridSize;
     553           3 :         m_Grid = new Grid<NavcellData>(m_GridSize, m_GridSize);
     554           3 :         SAFE_DELETE(m_TerrainOnlyGrid);
     555           3 :         m_TerrainOnlyGrid = new Grid<NavcellData>(m_GridSize, m_GridSize);
     556             : 
     557           3 :         m_DirtinessInformation = { true, true, Grid<std::uint8_t>(m_GridSize, m_GridSize) };
     558           3 :         m_AIPathfinderDirtinessInformation = m_DirtinessInformation;
     559             : 
     560           3 :         m_TerrainDirty = true;
     561             :     }
     562             : 
     563             :     // The grid should be properly initialized and clean. Checking the latter is expensive so do it only for debugging.
     564             : #ifdef NDEBUG
     565         189 :     ENSURE(m_DirtinessInformation.dirtinessGrid.compare_sizes(m_Grid));
     566             : #else
     567             :     ENSURE(m_DirtinessInformation.dirtinessGrid == Grid<std::uint8_t>(m_GridSize, m_GridSize));
     568             : #endif
     569             : 
     570         189 :     CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSimContext(), SYSTEM_ENTITY);
     571         189 :     cmpObstructionManager->UpdateInformations(m_DirtinessInformation);
     572             : 
     573         189 :     if (!m_DirtinessInformation.dirty && !m_TerrainDirty)
     574             :         return;
     575             : 
     576             :     // If the terrain has changed, recompute m_Grid
     577             :     // Else, use data from m_TerrainOnlyGrid and add obstructions
     578           6 :     if (m_TerrainDirty)
     579             :     {
     580           6 :         TerrainUpdateHelper();
     581             : 
     582           6 :         *m_Grid = *m_TerrainOnlyGrid;
     583             : 
     584           6 :         m_TerrainDirty = false;
     585           6 :         m_DirtinessInformation.globallyDirty = true;
     586             :     }
     587           0 :     else if (m_DirtinessInformation.globallyDirty)
     588             :     {
     589           0 :         ENSURE(m_Grid->compare_sizes(m_TerrainOnlyGrid));
     590           0 :         memcpy(m_Grid->m_Data, m_TerrainOnlyGrid->m_Data, (m_Grid->m_W)*(m_Grid->m_H)*sizeof(NavcellData));
     591             :     }
     592             :     else
     593             :     {
     594           0 :         ENSURE(m_Grid->compare_sizes(m_TerrainOnlyGrid));
     595             : 
     596           0 :         for (std::uint16_t j = 0; j < m_DirtinessInformation.dirtinessGrid.m_H; ++j)
     597           0 :             for (std::uint16_t i = 0; i < m_DirtinessInformation.dirtinessGrid.m_W; ++i)
     598           0 :                 if (m_DirtinessInformation.dirtinessGrid.get(i, j) == 1)
     599           0 :                     m_Grid->set(i, j, m_TerrainOnlyGrid->get(i, j));
     600             :     }
     601             : 
     602             :     // Add obstructions onto the grid
     603           6 :     cmpObstructionManager->Rasterize(*m_Grid, m_PassClasses, m_DirtinessInformation.globallyDirty);
     604             : 
     605             :     // Update the long-range and hierarchical pathfinders.
     606           6 :     if (m_DirtinessInformation.globallyDirty)
     607             :     {
     608           6 :         std::map<std::string, pass_class_t> nonPathfindingPassClasses, pathfindingPassClasses;
     609           6 :         GetPassabilityClasses(nonPathfindingPassClasses, pathfindingPassClasses);
     610           6 :         m_LongPathfinder->Reload(m_Grid);
     611           6 :         m_PathfinderHier->Recompute(m_Grid, nonPathfindingPassClasses, pathfindingPassClasses);
     612           6 :     }
     613             :     else
     614             :     {
     615           0 :         m_LongPathfinder->Update(m_Grid);
     616           0 :         m_PathfinderHier->Update(m_Grid, m_DirtinessInformation.dirtinessGrid);
     617             :     }
     618             : 
     619             :     // Remember the necessary updates that the AI pathfinder will have to perform as well
     620           6 :     m_AIPathfinderDirtinessInformation.MergeAndClear(m_DirtinessInformation);
     621         195 : }
     622             : 
     623           3 : void CCmpPathfinder::MinimalTerrainUpdate(int itile0, int jtile0, int itile1, int jtile1)
     624             : {
     625           3 :     TerrainUpdateHelper(false, itile0, jtile0, itile1, jtile1);
     626           3 : }
     627             : 
     628           9 : void CCmpPathfinder::TerrainUpdateHelper(bool expandPassability, int itile0, int jtile0, int itile1, int jtile1)
     629             : {
     630           9 :     PROFILE3("TerrainUpdateHelper");
     631             : 
     632           9 :     CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSimContext(), SYSTEM_ENTITY);
     633           9 :     CmpPtr<ICmpWaterManager> cmpWaterManager(GetSimContext(), SYSTEM_ENTITY);
     634           9 :     CmpPtr<ICmpTerrain> cmpTerrain(GetSimContext(), SYSTEM_ENTITY);
     635           9 :     CTerrain& terrain = GetSimContext().GetTerrain();
     636             : 
     637           9 :     if (!cmpTerrain || !cmpObstructionManager)
     638             :         return;
     639             : 
     640           9 :     std::uint16_t gridSize = cmpTerrain->GetMapSize() / Pathfinding::NAVCELL_SIZE_INT;
     641           9 :     if (gridSize == 0)
     642             :         return;
     643             : 
     644           9 :     const bool needsNewTerrainGrid = !m_TerrainOnlyGrid || m_GridSize != gridSize;
     645             :     if (needsNewTerrainGrid)
     646             :     {
     647           0 :         m_GridSize = gridSize;
     648             : 
     649           0 :         SAFE_DELETE(m_TerrainOnlyGrid);
     650           0 :         m_TerrainOnlyGrid = new Grid<NavcellData>(m_GridSize, m_GridSize);
     651             : 
     652             :         // If this update comes from a map resizing, we must reinitialize the other grids as well
     653           0 :         if (!m_TerrainOnlyGrid->compare_sizes(m_Grid))
     654             :         {
     655           0 :             SAFE_DELETE(m_Grid);
     656           0 :             m_Grid = new Grid<NavcellData>(m_GridSize, m_GridSize);
     657             : 
     658           0 :             m_DirtinessInformation = { true, true, Grid<std::uint8_t>(m_GridSize, m_GridSize) };
     659           0 :             m_AIPathfinderDirtinessInformation = m_DirtinessInformation;
     660             :         }
     661             :     }
     662             : 
     663           9 :     Grid<std::uint16_t> shoreGrid = ComputeShoreGrid();
     664             : 
     665          18 :     const bool partialTerrainGridUpdate =
     666             :         !expandPassability && !needsNewTerrainGrid &&
     667           9 :         itile0 != -1 && jtile0 != -1 && itile1 != -1 && jtile1 != -1;
     668           9 :     int istart = 0, iend = m_GridSize;
     669           9 :     int jstart = 0, jend = m_GridSize;
     670           9 :     if (partialTerrainGridUpdate)
     671             :     {
     672             :         // We need to extend the boundaries by 1 tile, because slope and ground
     673             :         // level are calculated by multiple neighboring tiles.
     674             :         // TODO: add CTerrain constant instead of 1.
     675           3 :         istart = Clamp<int>((itile0 - 1) * Pathfinding::NAVCELLS_PER_TERRAIN_TILE, 0, m_GridSize);
     676           3 :         iend = Clamp<int>((itile1 + 1) * Pathfinding::NAVCELLS_PER_TERRAIN_TILE, 0, m_GridSize);
     677           3 :         jstart = Clamp<int>((jtile0 - 1) * Pathfinding::NAVCELLS_PER_TERRAIN_TILE, 0, m_GridSize);
     678           3 :         jend = Clamp<int>((jtile1 + 1) * Pathfinding::NAVCELLS_PER_TERRAIN_TILE, 0, m_GridSize);
     679             :     }
     680             : 
     681             :     // Compute initial terrain-dependent passability
     682        6921 :     for (int j = jstart; j < jend; ++j)
     683             :     {
     684     5315328 :         for (int i = istart; i < iend; ++i)
     685             :         {
     686             :             // World-space coordinates for this navcell
     687     5308416 :             fixed x, z;
     688     5308416 :             Pathfinding::NavcellCenter(i, j, x, z);
     689             : 
     690             :             // Terrain-tile coordinates for this navcell
     691     5308416 :             int itile = i / Pathfinding::NAVCELLS_PER_TERRAIN_TILE;
     692     5308416 :             int jtile = j / Pathfinding::NAVCELLS_PER_TERRAIN_TILE;
     693             : 
     694             :             // Gather all the data potentially needed to determine passability:
     695             : 
     696     5308416 :             fixed height = terrain.GetExactGroundLevelFixed(x, z);
     697             : 
     698     5308416 :             fixed water;
     699     5308416 :             if (cmpWaterManager)
     700     5308416 :                 water = cmpWaterManager->GetWaterLevel(x, z);
     701             : 
     702     5308416 :             fixed depth = water - height;
     703             : 
     704             :             // Exact slopes give kind of weird output, so just use rough tile-based slopes
     705     5308416 :             fixed slope = terrain.GetSlopeFixed(itile, jtile);
     706             : 
     707             :             // Get world-space coordinates from shoreGrid (which uses terrain tiles)
     708     5308416 :             fixed shoredist = fixed::FromInt(shoreGrid.get(itile, jtile)).MultiplyClamp(TERRAIN_TILE_SIZE);
     709             : 
     710             :             // Compute the passability for every class for this cell
     711     5308416 :             NavcellData t = 0;
     712    53084160 :             for (const PathfinderPassability& passability : m_PassClasses)
     713    95551488 :                 if (!passability.IsPassable(depth, slope, shoredist))
     714    21233664 :                     t |= passability.m_Mask;
     715             : 
     716     5308416 :             m_TerrainOnlyGrid->set(i, j, t);
     717             :         }
     718             :     }
     719             : 
     720             :     // Compute off-world passability
     721           9 :     const int edgeSize = MAP_EDGE_TILES * Pathfinding::NAVCELLS_PER_TERRAIN_TILE;
     722             : 
     723           9 :     NavcellData edgeMask = 0;
     724          90 :     for (const PathfinderPassability& passability : m_PassClasses)
     725          81 :         edgeMask |= passability.m_Mask;
     726             : 
     727           9 :     int w = m_TerrainOnlyGrid->m_W;
     728           9 :     int h = m_TerrainOnlyGrid->m_H;
     729             : 
     730           9 :     if (cmpObstructionManager->GetPassabilityCircular())
     731             :     {
     732           0 :         for (int j = jstart; j < jend; ++j)
     733             :         {
     734           0 :             for (int i = istart; i < iend; ++i)
     735             :             {
     736             :                 // Based on CCmpRangeManager::LosIsOffWorld
     737             :                 // but tweaked since it's tile-based instead.
     738             :                 // (We double all the values so we can handle half-tile coordinates.)
     739             :                 // This needs to be slightly tighter than the LOS circle,
     740             :                 // else units might get themselves lost in the SoD around the edge.
     741             : 
     742           0 :                 int dist2 = (i*2 + 1 - w)*(i*2 + 1 - w)
     743           0 :                     + (j*2 + 1 - h)*(j*2 + 1 - h);
     744             : 
     745           0 :                 if (dist2 >= (w - 2*edgeSize) * (h - 2*edgeSize))
     746           0 :                     m_TerrainOnlyGrid->set(i, j, m_TerrainOnlyGrid->get(i, j) | edgeMask);
     747             :             }
     748             :         }
     749             :     }
     750             :     else
     751             :     {
     752        6921 :         for (std::uint16_t j = 0; j < h; ++j)
     753       89856 :             for (std::uint16_t i = 0; i < edgeSize; ++i)
     754       82944 :                 m_TerrainOnlyGrid->set(i, j, m_TerrainOnlyGrid->get(i, j) | edgeMask);
     755        6921 :         for (std::uint16_t j = 0; j < h; ++j)
     756       82944 :             for (std::uint16_t i = w-edgeSize+1; i < w; ++i)
     757       76032 :                 m_TerrainOnlyGrid->set(i, j, m_TerrainOnlyGrid->get(i, j) | edgeMask);
     758         117 :         for (std::uint16_t j = 0; j < edgeSize; ++j)
     759       80568 :             for (std::uint16_t i = edgeSize; i < w-edgeSize+1; ++i)
     760       80460 :                 m_TerrainOnlyGrid->set(i, j, m_TerrainOnlyGrid->get(i, j) | edgeMask);
     761         108 :         for (std::uint16_t j = h-edgeSize+1; j < h; ++j)
     762       73854 :             for (std::uint16_t i = edgeSize; i < w-edgeSize+1; ++i)
     763       73755 :                 m_TerrainOnlyGrid->set(i, j, m_TerrainOnlyGrid->get(i, j) | edgeMask);
     764             :     }
     765             : 
     766           9 :     if (!expandPassability)
     767           3 :         return;
     768             : 
     769             :     // Expand the impassability grid, for any class with non-zero clearance,
     770             :     // so that we can stop units getting too close to impassable navcells.
     771             :     // Note: It's not possible to perform this expansion once for all passabilities
     772             :     // with the same clearance, because the impassable cells are not necessarily the
     773             :     // same for all these passabilities.
     774          60 :     for (PathfinderPassability& passability : m_PassClasses)
     775             :     {
     776          54 :         if (passability.m_Clearance == fixed::Zero())
     777          30 :             continue;
     778             : 
     779          24 :         int clearance = (passability.m_Clearance / Pathfinding::NAVCELL_SIZE).ToInt_RoundToInfinity();
     780          24 :         ExpandImpassableCells(*m_TerrainOnlyGrid, clearance, passability.m_Mask);
     781             :     }
     782           9 : }
     783             : 
     784             : //////////////////////////////////////////////////////////
     785             : 
     786         954 : std::uint32_t CCmpPathfinder::ComputePathAsync(entity_pos_t x0, entity_pos_t z0, const PathGoal& goal,
     787             :     pass_class_t passClass, entity_id_t notify)
     788             : {
     789         954 :     LongPathRequest req = { m_NextAsyncTicket++, x0, z0, goal, passClass, notify };
     790         954 :     m_LongPathRequests.m_Requests.push_back(req);
     791         954 :     return req.ticket;
     792             : }
     793             : 
     794           0 : std::uint32_t CCmpPathfinder::ComputeShortPathAsync(entity_pos_t x0, entity_pos_t z0, entity_pos_t clearance, entity_pos_t range,
     795             :                                           const PathGoal& goal, pass_class_t passClass, bool avoidMovingUnits,
     796             :                                           entity_id_t group, entity_id_t notify)
     797             : {
     798           0 :     ShortPathRequest req = { m_NextAsyncTicket++, x0, z0, clearance, range, goal, passClass, avoidMovingUnits, group, notify };
     799           0 :     m_ShortPathRequests.m_Requests.push_back(req);
     800           0 :     return req.ticket;
     801             : }
     802             : 
     803           0 : void CCmpPathfinder::ComputePathImmediate(entity_pos_t x0, entity_pos_t z0, const PathGoal& goal, pass_class_t passClass, WaypointPath& ret) const
     804             : {
     805           0 :     m_LongPathfinder->ComputePath(*m_PathfinderHier, x0, z0, goal, passClass, ret);
     806           0 : }
     807             : 
     808           0 : WaypointPath CCmpPathfinder::ComputeShortPathImmediate(const ShortPathRequest& request) const
     809             : {
     810           0 :     return m_VertexPathfinders.front().ComputeShortPath(request, CmpPtr<ICmpObstructionManager>(GetSystemEntity()));
     811             : }
     812             : 
     813             : template<typename T>
     814             : template<typename U>
     815        1304 : void CCmpPathfinder::PathRequests<T>::Compute(const CCmpPathfinder& cmpPathfinder, const U& pathfinder)
     816             : {
     817             :     static_assert((std::is_same_v<T, LongPathRequest> && std::is_same_v<U, LongPathfinder>) ||
     818             :                   (std::is_same_v<T, ShortPathRequest> && std::is_same_v<U, VertexPathfinder>));
     819        1304 :     size_t maxN = m_Results.size();
     820        1304 :     size_t startIndex = m_Requests.size() - m_Results.size();
     821             :     do
     822             :     {
     823        2258 :         size_t workIndex = m_NextPathToCompute++;
     824        2258 :         if (workIndex >= maxN)
     825             :             break;
     826         954 :         const T& req = m_Requests[startIndex + workIndex];
     827         954 :         PathResult& result = m_Results[workIndex];
     828         954 :         result.ticket = req.ticket;
     829         954 :         result.notify = req.notify;
     830             :         if constexpr (std::is_same_v<T, LongPathRequest>)
     831         954 :             pathfinder.ComputePath(*cmpPathfinder.m_PathfinderHier, req.x0, req.z0, req.goal, req.passClass, result.path);
     832             :         else
     833           0 :             result.path = pathfinder.ComputeShortPath(req, CmpPtr<ICmpObstructionManager>(cmpPathfinder.GetSystemEntity()));
     834         954 :         if (workIndex == maxN - 1)
     835        2456 :             m_ComputeDone = true;
     836             :     }
     837             :     while (true);
     838        1304 : }
     839             : 
     840         540 : void CCmpPathfinder::SendRequestedPaths()
     841             : {
     842         540 :     PROFILE2("SendRequestedPaths");
     843             : 
     844         540 :     if (!m_LongPathRequests.m_ComputeDone || !m_ShortPathRequests.m_ComputeDone)
     845             :     {
     846             :         // Also start computing on the main thread to finish faster.
     847         163 :         m_ShortPathRequests.Compute(*this, m_VertexPathfinders.front());
     848         163 :         m_LongPathRequests.Compute(*this, *m_LongPathfinder);
     849             :     }
     850             :     // We're done, get the exceptions from the futures.
     851        2160 :     for (Future<void>& future : m_Futures)
     852        1620 :         if (future.Valid())
     853         486 :             future.Get();
     854             : 
     855         540 :     {
     856         540 :         PROFILE2("PostMessages");
     857         540 :         for (PathResult& path : m_ShortPathRequests.m_Results)
     858             :         {
     859           0 :             CMessagePathResult msg(path.ticket, path.path);
     860           0 :             GetSimContext().GetComponentManager().PostMessage(path.notify, msg);
     861           0 :         }
     862             : 
     863        1491 :         for (PathResult& path : m_LongPathRequests.m_Results)
     864             :         {
     865         951 :             CMessagePathResult msg(path.ticket, path.path);
     866         951 :             GetSimContext().GetComponentManager().PostMessage(path.notify, msg);
     867         951 :         }
     868           0 :     }
     869         540 :     m_ShortPathRequests.ClearComputed();
     870         540 :     m_LongPathRequests.ClearComputed();
     871         540 : }
     872             : 
     873         540 : void CCmpPathfinder::StartProcessingMoves(bool useMax)
     874             : {
     875         540 :     m_ShortPathRequests.PrepareForComputation(useMax ? m_MaxSameTurnMoves : 0);
     876         540 :     m_LongPathRequests.PrepareForComputation(useMax ? m_MaxSameTurnMoves : 0);
     877             : 
     878             :     // There's some overhead to waking threads, so don't do it unless we need to.
     879         540 :     const size_t m = std::min(m_Futures.size(), m_ShortPathRequests.m_Requests.size() + m_LongPathRequests.m_Requests.size());
     880        1029 :     for (size_t i = 0; i < m; ++i)
     881             :     {
     882         489 :         ENSURE(!m_Futures[i].Valid());
     883             :         // Pass the i+1th vertex pathfinder to keep the first for the main thread,
     884             :         // each thread get its own instance to avoid conflicts in cached data.
     885         489 :         m_Futures[i] = {g_TaskManager,
     886         489 :             [&pathfinder=*this, &vertexPfr=m_VertexPathfinders[i + 1]]()
     887             :             {
     888         489 :                 PROFILE2("Async pathfinding");
     889         489 :                 pathfinder.m_ShortPathRequests.Compute(pathfinder, vertexPfr);
     890         489 :                 pathfinder.m_LongPathRequests.Compute(pathfinder, *pathfinder.m_LongPathfinder);
     891         978 :             }};
     892             :     }
     893         540 : }
     894             : 
     895             : 
     896             : //////////////////////////////////////////////////////////
     897             : 
     898           0 : bool CCmpPathfinder::IsGoalReachable(entity_pos_t x0, entity_pos_t z0, const PathGoal& goal, pass_class_t passClass)
     899             : {
     900           0 :     PROFILE2("IsGoalReachable");
     901             : 
     902           0 :     std::uint16_t i, j;
     903           0 :     Pathfinding::NearestNavcell(x0, z0, i, j, m_GridSize, m_GridSize);
     904           0 :     if (!IS_PASSABLE(m_Grid->get(i, j), passClass))
     905           0 :         m_PathfinderHier->FindNearestPassableNavcell(i, j, passClass);
     906             : 
     907           0 :     return m_PathfinderHier->IsGoalReachable(i, j, goal, passClass);
     908           0 : }
     909             : 
     910           0 : std::vector<CFixedVector2D> CCmpPathfinder::DistributeAround(std::vector<entity_id_t> units, entity_pos_t x, entity_pos_t z) const
     911             : {
     912           0 :     PROFILE2("DistributeAround");
     913             : 
     914           0 :     std::vector<CFixedVector2D> positions;
     915           0 :     if (units.empty())
     916             :         return positions;
     917             : 
     918           0 :     positions.reserve(units.size());
     919             : 
     920             :     // Initialize spiral parameters
     921           0 :     fixed angle = fixed::Zero();
     922           0 :     fixed radius = fixed::FromInt(1);
     923           0 :     const fixed increment = fixed::FromInt(7) / 4;
     924             : 
     925             :     // Calculate the angle step so that at this radius we don't crowd the units
     926           0 :     fixed angleStep = fixed::FromInt(9).MulDiv(fixed::FromInt(1), fixed::Pi().Multiply(radius));
     927             : 
     928           0 :     for (size_t i = 0; i < units.size(); ++i)
     929             :     {
     930           0 :         CFixedVector2D offset(radius, fixed::Zero());
     931           0 :         offset = offset.Rotate(angle);
     932             : 
     933           0 :         positions.emplace_back(x + offset.X, z + offset.Y);
     934             : 
     935           0 :         angle += angleStep;
     936             :         // If we complete a circle, increase radius and recalculate angle step
     937           0 :         if (angle >= fixed::Pi().Multiply(fixed::FromInt(2)))
     938             :         {
     939           0 :             angle = fixed::Zero();
     940           0 :             radius += increment;
     941           0 :             angleStep = fixed::FromInt(9).MulDiv(fixed::FromInt(1), fixed::Pi().Multiply(radius));
     942             :         }
     943             :     }
     944             : 
     945             :     // Get current unit positions to calculate travel distances
     946           0 :     std::vector<CFixedVector2D> unitPositions;
     947           0 :     unitPositions.reserve(units.size());
     948             : 
     949           0 :     for (entity_id_t unit : units)
     950             :     {
     951           0 :         CmpPtr<ICmpPosition> unitPos(GetSimContext(), unit);
     952           0 :         if (!unitPos || !unitPos->IsInWorld())
     953           0 :             return positions;
     954             : 
     955           0 :         CFixedVector2D pos(unitPos->GetPosition2D());
     956           0 :         unitPositions.push_back(pos);
     957             :     }
     958             : 
     959             :     // Optimize positions by swapping them if it reduces total travel distance.
     960           0 :     bool improved;
     961           0 :     do
     962             :     {
     963           0 :         improved = false;
     964           0 :         for (size_t i = 0; i < positions.size(); ++i)
     965             :         {
     966             :             // Helper to compute squared distance between two points as integers
     967           0 :             auto distSq = [](const CFixedVector2D& p1, const CFixedVector2D& p2) -> std::uint32_t {
     968           0 :                 std::int32_t dx = (p1.X - p2.X).ToInt_RoundToInfinity();
     969           0 :                 std::int32_t dy = (p1.Y - p2.Y).ToInt_RoundToInfinity();
     970           0 :                 return dx*dx + dy*dy;
     971             :             };
     972             : 
     973           0 :             for (size_t j = i + 1; j < positions.size(); ++j)
     974             :             {
     975           0 :                 std::uint32_t currentDistSq = distSq(positions[i], unitPositions[i]) +
     976           0 :                     distSq(positions[j], unitPositions[j]);
     977           0 :                 std::uint32_t swappedDistSq = distSq(positions[j], unitPositions[i]) +
     978           0 :                     distSq(positions[i], unitPositions[j]);
     979             : 
     980             :                 // Swap if it reduces total squared distance
     981           0 :                 if (swappedDistSq < currentDistSq)
     982             :                 {
     983           0 :                     std::swap(positions[i], positions[j]);
     984           0 :                     improved = true;
     985             :                 }
     986             :             }
     987             :         }
     988             :     } while (improved);
     989             : 
     990             :     return positions;
     991           0 : }
     992             : 
     993       11349 : bool CCmpPathfinder::CheckMovement(const IObstructionTestFilter& filter,
     994             :     entity_pos_t x0, entity_pos_t z0, entity_pos_t x1, entity_pos_t z1, entity_pos_t r,
     995             :     pass_class_t passClass) const
     996             : {
     997             :     // Test against obstructions first. filter may discard pathfinding-blocking obstructions.
     998             :     // Use more permissive version of TestLine to allow unit-unit collisions to overlap slightly.
     999             :     // This makes movement smoother and more natural for units, overall.
    1000       11349 :     CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
    1001       11349 :     if (!cmpObstructionManager || cmpObstructionManager->TestLine(filter, x0, z0, x1, z1, r, true))
    1002           0 :         return false;
    1003             : 
    1004             :     // Then test against the terrain grid. This should not be necessary
    1005             :     // But in case we allow terrain to change it will become so.
    1006       11349 :     return Pathfinding::CheckLineMovement(x0, z0, x1, z1, passClass, *m_TerrainOnlyGrid);
    1007             : }
    1008             : 
    1009           0 : ICmpObstruction::EFoundationCheck CCmpPathfinder::CheckUnitPlacement(const IObstructionTestFilter& filter,
    1010             :     entity_pos_t x, entity_pos_t z, entity_pos_t r, pass_class_t passClass,
    1011             :     bool /*onlyCenterPoint*/) const
    1012             : {
    1013             :     // Check unit obstruction
    1014           0 :     CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
    1015           0 :     if (!cmpObstructionManager)
    1016             :         return ICmpObstruction::FOUNDATION_CHECK_FAIL_ERROR;
    1017             : 
    1018           0 :     if (cmpObstructionManager->TestUnitShape(filter, x, z, r, NULL))
    1019             :         return ICmpObstruction::FOUNDATION_CHECK_FAIL_OBSTRUCTS_FOUNDATION;
    1020             : 
    1021             :     // Test against terrain and static obstructions:
    1022             : 
    1023           0 :     std::uint16_t i, j;
    1024           0 :     Pathfinding::NearestNavcell(x, z, i, j, m_GridSize, m_GridSize);
    1025           0 :     if (!IS_PASSABLE(m_Grid->get(i, j), passClass))
    1026           0 :         return ICmpObstruction::FOUNDATION_CHECK_FAIL_TERRAIN_CLASS;
    1027             : 
    1028             :     // (Static obstructions will be redundantly tested against in both the
    1029             :     // obstruction-shape test and navcell-passability test, which is slightly
    1030             :     // inefficient but shouldn't affect behaviour)
    1031             : 
    1032             :     return ICmpObstruction::FOUNDATION_CHECK_SUCCESS;
    1033             : }
    1034             : 
    1035           0 : ICmpObstruction::EFoundationCheck CCmpPathfinder::CheckBuildingPlacement(const IObstructionTestFilter& filter,
    1036             :     entity_pos_t x, entity_pos_t z, entity_pos_t a, entity_pos_t w,
    1037             :     entity_pos_t h, entity_id_t id, pass_class_t passClass) const
    1038             : {
    1039           0 :     return CCmpPathfinder::CheckBuildingPlacement(filter, x, z, a, w, h, id, passClass, false);
    1040             : }
    1041             : 
    1042             : 
    1043           0 : ICmpObstruction::EFoundationCheck CCmpPathfinder::CheckBuildingPlacement(const IObstructionTestFilter& filter,
    1044             :     entity_pos_t x, entity_pos_t z, entity_pos_t a, entity_pos_t w,
    1045             :     entity_pos_t h, entity_id_t id, pass_class_t passClass, bool /*onlyCenterPoint*/) const
    1046             : {
    1047             :     // Check unit obstruction
    1048           0 :     CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
    1049           0 :     if (!cmpObstructionManager)
    1050             :         return ICmpObstruction::FOUNDATION_CHECK_FAIL_ERROR;
    1051             : 
    1052           0 :     if (cmpObstructionManager->TestStaticShape(filter, x, z, a, w, h, NULL))
    1053             :         return ICmpObstruction::FOUNDATION_CHECK_FAIL_OBSTRUCTS_FOUNDATION;
    1054             : 
    1055             :     // Test against terrain:
    1056             : 
    1057           0 :     ICmpObstructionManager::ObstructionSquare square;
    1058           0 :     CmpPtr<ICmpObstruction> cmpObstruction(GetSimContext(), id);
    1059           0 :     if (!cmpObstruction || !cmpObstruction->GetObstructionSquare(square))
    1060           0 :         return ICmpObstruction::FOUNDATION_CHECK_FAIL_NO_OBSTRUCTION;
    1061             : 
    1062           0 :     entity_pos_t expand;
    1063           0 :     const PathfinderPassability* passability = GetPassabilityFromMask(passClass);
    1064           0 :     if (passability)
    1065           0 :         expand = passability->m_Clearance;
    1066             : 
    1067           0 :     SimRasterize::Spans spans;
    1068           0 :     SimRasterize::RasterizeRectWithClearance(spans, square, expand, Pathfinding::NAVCELL_SIZE);
    1069           0 :     for (const SimRasterize::Span& span : spans)
    1070             :     {
    1071           0 :         std::int16_t i0 = span.i0;
    1072           0 :         std::int16_t i1 = span.i1;
    1073           0 :         std::int16_t j = span.j;
    1074             : 
    1075             :         // Fail if any span extends outside the grid
    1076           0 :         if (i0 < 0 || i1 > m_TerrainOnlyGrid->m_W || j < 0 || j >= m_TerrainOnlyGrid->m_H)
    1077             :             return ICmpObstruction::FOUNDATION_CHECK_FAIL_TERRAIN_CLASS;
    1078             : 
    1079             :         // Fail if any span includes an impassable tile
    1080           0 :         for (std::int16_t i = i0; i < i1; ++i)
    1081           0 :             if (!IS_PASSABLE(m_TerrainOnlyGrid->get(i, j), passClass))
    1082             :                 return ICmpObstruction::FOUNDATION_CHECK_FAIL_TERRAIN_CLASS;
    1083             :     }
    1084             : 
    1085             :     return ICmpObstruction::FOUNDATION_CHECK_SUCCESS;
    1086           0 : }
    1087             : 

Generated by: LCOV version 1.16