Pyrogenesis HEAD
Pyrogenesis, a RTS Engine
LongPathfinder.h
Go to the documentation of this file.
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_LONGPATHFINDER
19#define INCLUDED_LONGPATHFINDER
20
21#include "Pathfinding.h"
22
23#include "lib/code_generation.h"
24#include "lib/debug.h"
29
30#include <atomic>
31#include <map>
32#include <memory>
33#include <vector>
34
35/**
36 * Represents the 2D coordinates of a tile.
37 * The i/j components are packed into a single std::uint32_t, since we usually use these
38 * objects for equality comparisons and the VC2010 optimizer doesn't seem to automatically
39 * compare two std::uint16_ts in a single operation.
40 * TODO: maybe VC2012 will?
41 */
42struct TileID
43{
44 TileID() { }
45
46 TileID(std::uint16_t i, std::uint16_t j) : data((i << 16) | j) { }
47
48 bool operator==(const TileID& b) const
49 {
50 return data == b.data;
51 }
52
53 /// Returns lexicographic order over (i,j)
54 bool operator<(const TileID& b) const
55 {
56 return data < b.data;
57 }
58
59 std::uint16_t i() const { return data >> 16; }
60 std::uint16_t j() const { return data & 0xFFFF; }
61
62private:
63 std::uint32_t data;
64};
65
66/**
67 * Tile data for A* computation.
68 * (We store an array of one of these per terrain tile, so it ought to be optimised for size)
69 */
71{
72public:
73 enum {
77 };
78
79 bool IsUnexplored() const { return GetStatus() == STATUS_UNEXPLORED; }
80 bool IsOpen() const { return GetStatus() == STATUS_OPEN; }
81 bool IsClosed() const { return GetStatus() == STATUS_CLOSED; }
84
85 // Get pi,pj coords of predecessor to this tile on best path, given i,j coords of this tile
86 inline int GetPredI(int i) const { return i + GetPredDI(); }
87 inline int GetPredJ(int j) const { return j + GetPredDJ(); }
88
89 inline PathCost GetCost() const { return g; }
90 inline void SetCost(PathCost cost) { g = cost; }
91
92private:
93 PathCost g; // cost to reach this tile
94 std::uint32_t data; // 2-bit status; 15-bit PredI; 15-bit PredJ; packed for storage efficiency
95
96public:
97 inline std::uint8_t GetStatus() const
98 {
99 return data & 3;
100 }
101
102 inline void SetStatus(std::uint8_t s)
103 {
104 ASSERT(s < 4);
105 data &= ~3;
106 data |= (s & 3);
107 }
108
109 int GetPredDI() const
110 {
111 return static_cast<std::int32_t>(data) >> 17;
112 }
113
114 int GetPredDJ() const
115 {
116 return (static_cast<std::int32_t>(data) << 15) >> 17;
117 }
118
119 // Set the pi,pj coords of predecessor, given i,j coords of this tile
120 inline void SetPred(int pi, int pj, int i, int j)
121 {
122 int di = pi - i;
123 int dj = pj - j;
124 ASSERT(-16384 <= di && di < 16384);
125 ASSERT(-16384 <= dj && dj < 16384);
126 data &= 3;
127 data |= ((static_cast<std::uint32_t>(di) & 0x7FFF) << 17) |
128 ((static_cast<std::uint32_t>(dj) & 0x7FFF) << 2);
129 }
130};
131
133{
136};
137
140
141class JumpPointCache;
142
144{
145 std::uint32_t steps; // number of algorithm iterations
146
148
149 std::uint16_t iGoal, jGoal; // goal tile
150
152
154 // (there's no explicit closed list; it's encoded in PathfindTile)
155
158
159 PathCost hBest; // heuristic of closest discovered tile to goal
160 std::uint16_t iBest, jBest; // closest tile
161
163};
164
166
168
170{
171public:
174
175 void SetDebugOverlay(bool enabled);
176
177 void SetDebugPath(const HierarchicalPathfinder& hierPath, entity_pos_t x0, entity_pos_t z0, const PathGoal& goal, pass_class_t passClass)
178 {
179 if (!m_Debug.Overlay)
180 return;
181
183 delete m_Debug.Path;
184 m_Debug.Path = new WaypointPath();
185 ComputePath(hierPath, x0, z0, goal, passClass, *m_Debug.Path);
186 m_Debug.PassClass = passClass;
187 }
188
189 void Reload(Grid<NavcellData>* passabilityGrid)
190 {
191 m_Grid = passabilityGrid;
192 ASSERT(passabilityGrid->m_H == passabilityGrid->m_W);
193 m_GridSize = passabilityGrid->m_W;
194
195 m_JumpPointCache.clear();
196 }
197
198 void Update(Grid<NavcellData>* passabilityGrid)
199 {
200 m_Grid = passabilityGrid;
201 ASSERT(passabilityGrid->m_H == passabilityGrid->m_W);
202 ASSERT(m_GridSize == passabilityGrid->m_H);
203
204 m_JumpPointCache.clear();
205 }
206
207 /**
208 * Compute a tile-based path from the given point to the goal, and return the set of waypoints.
209 * The waypoints correspond to the centers of horizontally/vertically adjacent tiles
210 * along the path.
211 */
212 void ComputePath(const HierarchicalPathfinder& hierPath, entity_pos_t x0, entity_pos_t z0, const PathGoal& origGoal,
213 pass_class_t passClass, WaypointPath& path) const;
214
215 /**
216 * Compute a tile-based path from the given point to the goal, excluding the regions
217 * specified in excludedRegions (which are treated as impassable) and return the set of waypoints.
218 * The waypoints correspond to the centers of horizontally/vertically adjacent tiles
219 * along the path.
220 */
221 void ComputePath(const HierarchicalPathfinder& hierPath, entity_pos_t x0, entity_pos_t z0, const PathGoal& origGoal,
222 pass_class_t passClass, std::vector<CircularRegion> excludedRegions, WaypointPath& path);
223
224 void GetDebugData(std::uint32_t& steps, double& time, Grid<std::uint8_t>& grid) const
225 {
226 GetDebugDataJPS(steps, time, grid);
227 }
228
230 std::uint16_t m_GridSize;
231
232 // Debugging - output from last pathfind operation.
233 struct Debug
234 {
235 /**
236 * Atomic - used to toggle debugging.
237 *
238 * Terrain overlay for pathfinder debugging.
239 * Renders a representation of the most recent pathfinding operation.
240 */
241 std::atomic<TerrainTextureOverlay*> Overlay = nullptr;
242 // Mutable - set by ComputeJPSPath (thus possibly from different threads).
243 // Synchronized via mutex if necessary.
244 mutable PathfindTileGrid* Grid = nullptr;
245 mutable std::uint32_t Steps;
246 mutable double Time;
247 mutable PathGoal Goal;
248
249 WaypointPath* Path = nullptr;
252
253private:
254 PathCost CalculateHeuristic(int i, int j, int iGoal, int jGoal) const;
255 void ProcessNeighbour(int pi, int pj, int i, int j, PathCost pg, PathfinderState& state) const;
256
257 /**
258 * JPS algorithm helper functions
259 * @param detectGoal is not used if m_UseJPSCache is true
260 */
261 void AddJumpedHoriz(int i, int j, int di, PathCost g, PathfinderState& state, bool detectGoal) const;
262 int HasJumpedHoriz(int i, int j, int di, PathfinderState& state, bool detectGoal) const;
263 void AddJumpedVert(int i, int j, int dj, PathCost g, PathfinderState& state, bool detectGoal) const;
264 int HasJumpedVert(int i, int j, int dj, PathfinderState& state, bool detectGoal) const;
265 void AddJumpedDiag(int i, int j, int di, int dj, PathCost g, PathfinderState& state) const;
266
267 /**
268 * See LongPathfinder.cpp for implementation details
269 * TODO: cleanup documentation
270 */
271 void ComputeJPSPath(const HierarchicalPathfinder& hierPath, entity_pos_t x0, entity_pos_t z0, const PathGoal& origGoal, pass_class_t passClass, WaypointPath& path) const;
272 void GetDebugDataJPS(std::uint32_t& steps, double& time, Grid<std::uint8_t>& grid) const;
273
274 // Helper functions for ComputePath
275
276 /**
277 * Given a path with an arbitrary collection of waypoints, updates the
278 * waypoints to be nicer.
279 * If @param maxDist is non-zero, path waypoints will be espaced by at most @param maxDist.
280 * In that case the distance between (x0, z0) and the first waypoint will also be made less than maxDist.
281 */
282 void ImprovePathWaypoints(WaypointPath& path, pass_class_t passClass, entity_pos_t maxDist, entity_pos_t x0, entity_pos_t z0) const;
283
284 /**
285 * Generate a passability map, stored in the 16th bit of navcells, based on passClass,
286 * but with a set of impassable circular regions.
287 */
288 void GenerateSpecialMap(pass_class_t passClass, std::vector<CircularRegion> excludedRegions);
289
291 // Mutable may be used here as caching does not change the external const-ness of the Long Range pathfinder.
292 // This is thread-safe as it is order independent (no change in the output of the function for a given set of params).
293 // Obviously, this means that the cache should actually be a cache and not return different results
294 // from what would happen if things hadn't been cached.
295 mutable std::map<pass_class_t, std::shared_ptr<JumpPointCache>> m_JumpPointCache;
296};
297
298#endif // INCLUDED_LONGPATHFINDER
PriorityQueueHeap< TileID, PathCost, PathCost > PriorityQueue
Definition: LongPathfinder.h:138
SparseGrid< PathfindTile > PathfindTileGrid
Definition: LongPathfinder.h:139
std::uint16_t pass_class_t
Definition: Pathfinding.h:33
Entity coordinate types.
A simple fixed-point number class.
Definition: Fixed.h:129
std::uint16_t m_W
Definition: Grid.h:242
std::uint16_t m_H
Definition: Grid.h:242
Definition: HierarchicalPathfinder.h:71
Jump point cache.
Definition: LongPathfinder.cpp:137
Definition: LongPathfinder.h:170
int HasJumpedVert(int i, int j, int dj, PathfinderState &state, bool detectGoal) const
Definition: LongPathfinder.cpp:715
LongPathfinder()
Definition: LongPathfinder.cpp:454
Grid< NavcellData > * m_Grid
Definition: LongPathfinder.h:229
void SetDebugOverlay(bool enabled)
Definition: LongPathfinder.cpp:467
void ComputePath(const HierarchicalPathfinder &hierPath, entity_pos_t x0, entity_pos_t z0, const PathGoal &origGoal, pass_class_t passClass, WaypointPath &path) const
Compute a tile-based path from the given point to the goal, and return the set of waypoints.
Definition: LongPathfinder.cpp:1091
~LongPathfinder()
Definition: LongPathfinder.cpp:460
int HasJumpedHoriz(int i, int j, int di, PathfinderState &state, bool detectGoal) const
Definition: LongPathfinder.cpp:637
bool m_UseJPSCache
Definition: LongPathfinder.h:290
std::uint16_t m_GridSize
Definition: LongPathfinder.h:230
void AddJumpedVert(int i, int j, int dj, PathCost g, PathfinderState &state, bool detectGoal) const
Definition: LongPathfinder.cpp:673
void AddJumpedDiag(int i, int j, int di, int dj, PathCost g, PathfinderState &state) const
Definition: LongPathfinder.cpp:755
void Update(Grid< NavcellData > *passabilityGrid)
Definition: LongPathfinder.h:198
void ComputeJPSPath(const HierarchicalPathfinder &hierPath, entity_pos_t x0, entity_pos_t z0, const PathGoal &origGoal, pass_class_t passClass, WaypointPath &path) const
See LongPathfinder.cpp for implementation details TODO: cleanup documentation.
Definition: LongPathfinder.cpp:806
PathCost CalculateHeuristic(int i, int j, int iGoal, int jGoal) const
Definition: LongPathfinder.cpp:482
void GenerateSpecialMap(pass_class_t passClass, std::vector< CircularRegion > excludedRegions)
Generate a passability map, stored in the 16th bit of navcells, based on passClass,...
Definition: LongPathfinder.cpp:1117
void ProcessNeighbour(int pi, int pj, int i, int j, PathCost pg, PathfinderState &state) const
Definition: LongPathfinder.cpp:491
std::map< pass_class_t, std::shared_ptr< JumpPointCache > > m_JumpPointCache
Definition: LongPathfinder.h:295
void ImprovePathWaypoints(WaypointPath &path, pass_class_t passClass, entity_pos_t maxDist, entity_pos_t x0, entity_pos_t z0) const
Given a path with an arbitrary collection of waypoints, updates the waypoints to be nicer.
Definition: LongPathfinder.cpp:1013
void AddJumpedHoriz(int i, int j, int di, PathCost g, PathfinderState &state, bool detectGoal) const
JPS algorithm helper functions.
Definition: LongPathfinder.cpp:595
void SetDebugPath(const HierarchicalPathfinder &hierPath, entity_pos_t x0, entity_pos_t z0, const PathGoal &goal, pass_class_t passClass)
Definition: LongPathfinder.h:177
void Reload(Grid< NavcellData > *passabilityGrid)
Definition: LongPathfinder.h:189
struct LongPathfinder::Debug m_Debug
void GetDebugDataJPS(std::uint32_t &steps, double &time, Grid< std::uint8_t > &grid) const
Definition: LongPathfinder.cpp:1065
void GetDebugData(std::uint32_t &steps, double &time, Grid< std::uint8_t > &grid) const
Definition: LongPathfinder.h:224
Pathfinder goal.
Definition: PathGoal.h:34
Definition: path.h:84
Similar to Grid, except optimised for sparse usage (the grid is subdivided into buckets whose content...
Definition: Grid.h:304
Base class for texture-based terrain overlays, with an arbitrary number of texels per terrain tile,...
Definition: TerrainOverlay.h:202
#define SAFE_DELETE(p)
delete memory ensuing from new and set the pointer to zero (thus making double-frees safe / a no-op)
Definition: code_generation.h:111
#define ASSERT(expr)
same as ENSURE in debug mode, does nothing in release mode.
Definition: debug.h:250
enum PS::Loader::anonymous_namespace{Loader.cpp}::@26 state
Definition: LongPathfinder.h:133
CircularRegion(entity_pos_t x, entity_pos_t z, entity_pos_t r)
Definition: LongPathfinder.h:134
entity_pos_t z
Definition: LongPathfinder.h:135
entity_pos_t x
Definition: LongPathfinder.h:135
entity_pos_t r
Definition: LongPathfinder.h:135
Definition: LongPathfinder.h:234
double Time
Definition: LongPathfinder.h:246
WaypointPath * Path
Definition: LongPathfinder.h:249
PathGoal Goal
Definition: LongPathfinder.h:247
PathfindTileGrid * Grid
Definition: LongPathfinder.h:244
std::uint32_t Steps
Definition: LongPathfinder.h:245
pass_class_t PassClass
Definition: LongPathfinder.h:250
std::atomic< TerrainTextureOverlay * > Overlay
Atomic - used to toggle debugging.
Definition: LongPathfinder.h:241
Represents the cost of a path consisting of horizontal/vertical and diagonal movements over a uniform...
Definition: Pathfinding.h:79
Tile data for A* computation.
Definition: LongPathfinder.h:71
bool IsOpen() const
Definition: LongPathfinder.h:80
int GetPredI(int i) const
Definition: LongPathfinder.h:86
int GetPredJ(int j) const
Definition: LongPathfinder.h:87
std::uint32_t data
Definition: LongPathfinder.h:94
PathCost g
Definition: LongPathfinder.h:93
@ STATUS_OPEN
Definition: LongPathfinder.h:75
@ STATUS_CLOSED
Definition: LongPathfinder.h:76
@ STATUS_UNEXPLORED
Definition: LongPathfinder.h:74
int GetPredDI() const
Definition: LongPathfinder.h:109
void SetCost(PathCost cost)
Definition: LongPathfinder.h:90
void SetPred(int pi, int pj, int i, int j)
Definition: LongPathfinder.h:120
bool IsClosed() const
Definition: LongPathfinder.h:81
int GetPredDJ() const
Definition: LongPathfinder.h:114
void SetStatusClosed()
Definition: LongPathfinder.h:83
void SetStatusOpen()
Definition: LongPathfinder.h:82
std::uint8_t GetStatus() const
Definition: LongPathfinder.h:97
PathCost GetCost() const
Definition: LongPathfinder.h:89
void SetStatus(std::uint8_t s)
Definition: LongPathfinder.h:102
bool IsUnexplored() const
Definition: LongPathfinder.h:79
Definition: LongPathfinder.h:144
PathCost hBest
Definition: LongPathfinder.h:159
const JumpPointCache * jpc
Definition: LongPathfinder.h:162
std::uint16_t jBest
Definition: LongPathfinder.h:160
Grid< NavcellData > * terrain
Definition: LongPathfinder.h:157
PriorityQueue open
Definition: LongPathfinder.h:153
std::uint16_t jGoal
Definition: LongPathfinder.h:149
PathfindTileGrid * tiles
Definition: LongPathfinder.h:156
pass_class_t passClass
Definition: LongPathfinder.h:151
std::uint16_t iBest
Definition: LongPathfinder.h:160
std::uint16_t iGoal
Definition: LongPathfinder.h:149
PathGoal goal
Definition: LongPathfinder.h:147
std::uint32_t steps
Definition: LongPathfinder.h:145
Represents the 2D coordinates of a tile.
Definition: LongPathfinder.h:43
TileID(std::uint16_t i, std::uint16_t j)
Definition: LongPathfinder.h:46
TileID()
Definition: LongPathfinder.h:44
std::uint32_t data
Definition: LongPathfinder.h:63
std::uint16_t j() const
Definition: LongPathfinder.h:60
bool operator<(const TileID &b) const
Returns lexicographic order over (i,j)
Definition: LongPathfinder.h:54
bool operator==(const TileID &b) const
Definition: LongPathfinder.h:48
std::uint16_t i() const
Definition: LongPathfinder.h:59
Returned path.
Definition: Pathfinding.h:69