Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "precompiled.h"
19 :
20 : #include "LongPathfinder.h"
21 :
22 : #include "graphics/SColor.h"
23 : #include "maths/Fixed.h"
24 : #include "maths/FixedVector2D.h"
25 : #include "ps/CLogger.h"
26 : #include "ps/Profiler2.h"
27 : #include "renderer/TerrainOverlay.h"
28 : #include "simulation2/helpers/HierarchicalPathfinder.h"
29 : #include "simulation2/helpers/Pathfinding.h"
30 :
31 : #include <algorithm>
32 : #include <bit>
33 : #include <cmath>
34 : #include <cstddef>
35 : #include <mutex>
36 : #include <utility>
37 :
38 : namespace
39 : {
40 : static std::mutex g_DebugMutex;
41 :
42 0 : void BuildTextureRGBA(LongPathfinder& pathfinder, std::uint8_t* data, std::size_t w, std::size_t h)
43 : {
44 : // Grab the debug data for the most recently generated path
45 0 : std::uint32_t steps;
46 0 : double time;
47 0 : Grid<std::uint8_t> debugGrid;
48 0 : pathfinder.GetDebugData(steps, time, debugGrid);
49 :
50 : // Render navcell passability
51 0 : TerrainTextureOverlay::OverwriteEachTile(data, w, h, [&](const int i, const int j)
52 : {
53 0 : if (debugGrid.m_W && debugGrid.m_H)
54 : {
55 0 : if (pathfinder.m_Debug.Goal.NavcellContainsGoal(i, j))
56 0 : return SColor4ub(0, 0, 255, 127);
57 :
58 0 : const std::uint8_t n{debugGrid.get(i, j)};
59 0 : if (n == 1)
60 0 : return SColor4ub(255, 255, 0, 127);
61 0 : if (n == 2)
62 0 : return SColor4ub(0, 255, 0, 127);
63 : }
64 0 : if (!IS_PASSABLE(pathfinder.m_Grid->get(j, i), pathfinder.m_Debug.PassClass))
65 0 : return SColor4ub(255, 0, 0, 127);
66 0 : return SColor4ub{0, 0, 0, 0};
67 : });
68 :
69 : // Render the most recently generated path
70 0 : if (pathfinder.m_Debug.Path && !pathfinder.m_Debug.Path->m_Waypoints.empty())
71 : {
72 : std::vector<Waypoint>& waypoints = pathfinder.m_Debug.Path->m_Waypoints;
73 : std::uint16_t ip = 0, jp = 0;
74 0 : for (size_t k = 0; k < waypoints.size(); ++k)
75 : {
76 0 : std::uint16_t i, j;
77 0 : Pathfinding::NearestNavcell(waypoints[k].x, waypoints[k].z, i, j, pathfinder.m_GridSize,
78 0 : pathfinder.m_GridSize);
79 0 : if (k == 0)
80 : {
81 : ip = i;
82 : jp = j;
83 : }
84 : else
85 : {
86 : bool firstCell = true;
87 0 : do
88 : {
89 0 : if (data[(jp*w + ip)*4+3] == 0)
90 : {
91 0 : data[(jp*w + ip)*4+0] = 0xFF;
92 0 : data[(jp*w + ip)*4+1] = 0xFF;
93 0 : data[(jp*w + ip)*4+2] = 0xFF;
94 0 : data[(jp*w + ip)*4+3] = firstCell ? 0xA0 : 0x60;
95 : }
96 0 : ip = ip < i ? ip+1 : ip > i ? ip-1 : ip;
97 0 : jp = jp < j ? jp+1 : jp > j ? jp-1 : jp;
98 0 : firstCell = false;
99 : }
100 0 : while (ip != i || jp != j);
101 : }
102 : }
103 : }
104 0 : }
105 : }
106 :
107 : /**
108 : * Jump point cache.
109 : *
110 : * The JPS algorithm wants to efficiently either find the first jump point
111 : * in some direction from some cell (not counting the cell itself),
112 : * if it is reachable without crossing any impassable cells;
113 : * or know that there is no such reachable jump point.
114 : * The jump point is always on a passable cell.
115 : * We cache that data to allow fast lookups, which helps performance
116 : * significantly (especially on sparse maps).
117 : * Recalculation might be expensive but the underlying passability data
118 : * changes relatively rarely.
119 : *
120 : * To allow the algorithm to detect goal cells, we want to treat them as
121 : * jump points too. (That means the algorithm will push those cells onto
122 : * its open queue, and will eventually pop a goal cell and realise it's done.)
123 : * (Goals might be circles/squares/etc, not just a single cell.)
124 : * But the goal generally changes for every path request, so we can't cache
125 : * it like the normal jump points.
126 : * Instead, if there's no jump point from some cell then we'll cache the
127 : * first impassable cell as an 'obstruction jump point'
128 : * (with a flag to distinguish from a real jump point), and then the caller
129 : * can test whether the goal includes a cell that's closer than the first
130 : * (obstruction or real) jump point,
131 : * and treat the goal cell as a jump point in that case.
132 : *
133 : * We only ever need to find the jump point relative to a passable cell;
134 : * the cache is allowed to return bogus values for impassable cells.
135 : */
136 0 : class JumpPointCache
137 : {
138 : /**
139 : * Simple space-inefficient row storage.
140 : */
141 0 : struct RowRaw
142 : {
143 : std::vector<std::uint16_t> data;
144 :
145 0 : size_t GetMemoryUsage() const
146 : {
147 0 : return data.capacity() * sizeof(std::uint16_t);
148 : }
149 :
150 0 : RowRaw(int length)
151 0 : {
152 0 : data.resize(length);
153 0 : }
154 :
155 : /**
156 : * Set cells x0 <= x < x1 to have jump point x1.
157 : */
158 0 : void SetRange(int x0, int x1, bool obstruction)
159 : {
160 0 : ENSURE(0 <= x0 && x0 <= x1 && x1 < (int)data.size());
161 0 : for (int x = x0; x < x1; ++x)
162 0 : data[x] = (x1 << 1) | (obstruction ? 1 : 0);
163 0 : }
164 :
165 : /**
166 : * Returns the coordinate of the next jump point xp (where x < xp),
167 : * and whether it's an obstruction point or jump point.
168 : */
169 0 : void Get(int x, int& xp, bool& obstruction) const
170 : {
171 0 : ENSURE(0 <= x && x < (int)data.size());
172 0 : xp = data[x] >> 1;
173 0 : obstruction = data[x] & 1;
174 0 : }
175 :
176 : void Finish() { }
177 : };
178 :
179 : struct RowTree
180 : {
181 : /**
182 : * Represents an interval [u15 x0, u16 x1)
183 : * with a boolean obstruction flag,
184 : * packed into a single std::uint32_t.
185 : */
186 : struct Interval
187 : {
188 : Interval() : data(0) { }
189 :
190 : Interval(int x0, int x1, bool obstruction)
191 : {
192 : ENSURE(0 <= x0 && x0 < 0x8000);
193 : ENSURE(0 <= x1 && x1 < 0x10000);
194 : data = static_cast<std::uint32_t>(x0 << 17) |
195 : static_cast<std::uint32_t>(obstruction ? 0x10000 : 0) |
196 : static_cast<std::uint32_t>(x1);
197 : }
198 :
199 : int x0() { return data >> 17; }
200 : int x1() { return data & 0xFFFF; }
201 : bool obstruction() { return (data & 0x10000) != 0; }
202 :
203 : std::uint32_t data;
204 : };
205 :
206 : std::vector<Interval> data;
207 :
208 : size_t GetMemoryUsage() const
209 : {
210 : return data.capacity() * sizeof(Interval);
211 : }
212 :
213 : RowTree(int /*length*/)
214 : {
215 : }
216 :
217 : void SetRange(int x0, int x1, bool obstruction)
218 : {
219 : ENSURE(0 <= x0 && x0 <= x1);
220 : data.emplace_back(x0, x1, obstruction);
221 : }
222 :
223 : /**
224 : * Recursive helper function for Finish().
225 : * Given two ranges [x0, pivot) and [pivot, x1) in the sorted array 'data',
226 : * the pivot element is added onto the binary tree (stored flattened in an
227 : * array), and then each range is split into two sub-ranges with a pivot in
228 : * the middle (to ensure the tree remains balanced) and ConstructTree recurses.
229 : */
230 : void ConstructTree(std::vector<Interval>& tree, size_t x0, size_t pivot, size_t x1, size_t idx_tree)
231 : {
232 : ENSURE(x0 < data.size());
233 : ENSURE(x1 <= data.size());
234 : ENSURE(x0 <= pivot);
235 : ENSURE(pivot < x1);
236 : ENSURE(idx_tree < tree.size());
237 :
238 : tree[idx_tree] = data[pivot];
239 :
240 : if (x0 < pivot)
241 : ConstructTree(tree, x0, (x0 + pivot) / 2, pivot, (idx_tree << 1) + 1);
242 : if (pivot + 1 < x1)
243 : ConstructTree(tree, pivot + 1, (pivot + x1) / 2, x1, (idx_tree << 1) + 2);
244 : }
245 :
246 : void Finish()
247 : {
248 : // Convert the sorted interval list into a balanced binary tree
249 :
250 : std::vector<Interval> tree;
251 :
252 : if (!data.empty())
253 : {
254 : size_t depth = std::bit_width(data.size());
255 : tree.resize((1 << depth) - 1);
256 : ConstructTree(tree, 0, data.size() / 2, data.size(), 0);
257 : }
258 :
259 : data.swap(tree);
260 : }
261 :
262 : void Get(int x, int& xp, bool& obstruction) const
263 : {
264 : // Search the binary tree for an interval which contains x
265 : int i = 0;
266 : while (true)
267 : {
268 : ENSURE(i < (int)data.size());
269 : Interval interval = data[i];
270 : if (x < interval.x0())
271 : i = (i << 1) + 1;
272 : else if (x >= interval.x1())
273 : i = (i << 1) + 2;
274 : else
275 : {
276 : ENSURE(interval.x0() <= x && x < interval.x1());
277 : xp = interval.x1();
278 : obstruction = interval.obstruction();
279 : return;
280 : }
281 : }
282 : }
283 : };
284 :
285 : // Pick one of the row implementations
286 : typedef RowRaw Row;
287 :
288 : public:
289 : int m_Width;
290 : int m_Height;
291 : std::vector<Row> m_JumpPointsRight;
292 : std::vector<Row> m_JumpPointsLeft;
293 : std::vector<Row> m_JumpPointsUp;
294 : std::vector<Row> m_JumpPointsDown;
295 :
296 : /**
297 : * Compute the cached obstruction/jump points for each cell,
298 : * in a single direction. By default the code assumes the rightwards
299 : * (+i) direction; set 'transpose' to switch to upwards (+j),
300 : * and/or set 'mirror' to reverse the direction.
301 : */
302 0 : void ComputeRows(std::vector<Row>& rows,
303 : const Grid<NavcellData>& terrain, pass_class_t passClass,
304 : bool transpose, bool mirror)
305 : {
306 0 : int w = terrain.m_W;
307 0 : int h = terrain.m_H;
308 :
309 0 : if (transpose)
310 0 : std::swap(w, h);
311 :
312 : // Check the terrain passability, adjusted for transpose/mirror
313 : #define TERRAIN_IS_PASSABLE(i, j) \
314 : IS_PASSABLE( \
315 : mirror \
316 : ? (transpose ? terrain.get((j), w-1-(i)) : terrain.get(w-1-(i), (j))) \
317 : : (transpose ? terrain.get((j), (i)) : terrain.get((i), (j))) \
318 : , passClass)
319 :
320 0 : rows.reserve(h);
321 0 : for (int j = 0; j < h; ++j)
322 0 : rows.emplace_back(w);
323 :
324 0 : for (int j = 1; j < h - 1; ++j)
325 : {
326 : // Find the first passable cell.
327 : // Then, find the next jump/obstruction point after that cell,
328 : // and store that point for the passable range up to that cell,
329 : // then repeat.
330 :
331 : int i = 0;
332 0 : while (i < w)
333 : {
334 : // Restart the 'while' loop until we reach a passable cell
335 0 : if (!TERRAIN_IS_PASSABLE(i, j))
336 : {
337 0 : ++i;
338 0 : continue;
339 : }
340 :
341 : // i is now a passable cell; find the next jump/obstruction point.
342 : // (We assume the map is surrounded by impassable cells, so we don't
343 : // need to explicitly check for world bounds here.)
344 :
345 : int i0 = i;
346 0 : while (true)
347 : {
348 0 : ++i;
349 :
350 : // Check if we hit an obstructed tile
351 0 : if (!TERRAIN_IS_PASSABLE(i, j))
352 : {
353 0 : rows[j].SetRange(i0, i, true);
354 : break;
355 : }
356 :
357 : // Check if we reached a jump point
358 0 : if ((!TERRAIN_IS_PASSABLE(i - 1, j - 1) && TERRAIN_IS_PASSABLE(i, j - 1)) ||
359 0 : (!TERRAIN_IS_PASSABLE(i - 1, j + 1) && TERRAIN_IS_PASSABLE(i, j + 1)))
360 : {
361 0 : rows[j].SetRange(i0, i, false);
362 : break;
363 : }
364 : }
365 : }
366 :
367 0 : rows[j].Finish();
368 : }
369 : #undef TERRAIN_IS_PASSABLE
370 0 : }
371 :
372 0 : void reset(const Grid<NavcellData>* terrain, pass_class_t passClass)
373 : {
374 0 : PROFILE2("JumpPointCache reset");
375 :
376 0 : m_Width = terrain->m_W;
377 0 : m_Height = terrain->m_H;
378 :
379 0 : ComputeRows(m_JumpPointsRight, *terrain, passClass, false, false);
380 0 : ComputeRows(m_JumpPointsLeft, *terrain, passClass, false, true);
381 0 : ComputeRows(m_JumpPointsUp, *terrain, passClass, true, false);
382 0 : ComputeRows(m_JumpPointsDown, *terrain, passClass, true, true);
383 0 : }
384 :
385 0 : size_t GetMemoryUsage() const
386 : {
387 0 : size_t bytes = 0;
388 0 : for (int i = 0; i < m_Width; ++i)
389 : {
390 0 : bytes += m_JumpPointsUp[i].GetMemoryUsage();
391 0 : bytes += m_JumpPointsDown[i].GetMemoryUsage();
392 : }
393 0 : for (int j = 0; j < m_Height; ++j)
394 : {
395 0 : bytes += m_JumpPointsRight[j].GetMemoryUsage();
396 0 : bytes += m_JumpPointsLeft[j].GetMemoryUsage();
397 : }
398 0 : return bytes;
399 : }
400 :
401 : /**
402 : * Returns the next jump point (or goal point) to explore,
403 : * at (ip, j) where i < ip.
404 : * Returns i if there is no such point.
405 : */
406 0 : int GetJumpPointRight(int i, int j, const PathGoal& goal) const
407 : {
408 0 : int ip;
409 0 : bool obstruction;
410 0 : m_JumpPointsRight[j].Get(i, ip, obstruction);
411 : // Adjust ip to be a goal cell, if there is one closer than the jump point;
412 : // and then return the new ip if there is a goal,
413 : // or the old ip if there is a (non-obstruction) jump point
414 0 : if (goal.NavcellRectContainsGoal(i + 1, j, ip - 1, j, &ip, NULL) || !obstruction)
415 0 : return ip;
416 : return i;
417 : }
418 :
419 0 : int GetJumpPointLeft(int i, int j, const PathGoal& goal) const
420 : {
421 0 : int mip; // mirrored value, because m_JumpPointsLeft is generated from a mirrored map
422 0 : bool obstruction;
423 0 : m_JumpPointsLeft[j].Get(m_Width - 1 - i, mip, obstruction);
424 0 : int ip = m_Width - 1 - mip;
425 0 : if (goal.NavcellRectContainsGoal(i - 1, j, ip + 1, j, &ip, NULL) || !obstruction)
426 0 : return ip;
427 : return i;
428 : }
429 :
430 0 : int GetJumpPointUp(int i, int j, const PathGoal& goal) const
431 : {
432 0 : int jp;
433 0 : bool obstruction;
434 0 : m_JumpPointsUp[i].Get(j, jp, obstruction);
435 0 : if (goal.NavcellRectContainsGoal(i, j + 1, i, jp - 1, NULL, &jp) || !obstruction)
436 0 : return jp;
437 : return j;
438 : }
439 :
440 0 : int GetJumpPointDown(int i, int j, const PathGoal& goal) const
441 : {
442 0 : int mjp; // mirrored value
443 0 : bool obstruction;
444 0 : m_JumpPointsDown[i].Get(m_Height - 1 - j, mjp, obstruction);
445 0 : int jp = m_Height - 1 - mjp;
446 0 : if (goal.NavcellRectContainsGoal(i, j - 1, i, jp + 1, NULL, &jp) || !obstruction)
447 0 : return jp;
448 : return j;
449 : }
450 : };
451 :
452 : //////////////////////////////////////////////////////////
453 :
454 11 : LongPathfinder::LongPathfinder() :
455 11 : m_UseJPSCache(false),
456 11 : m_Grid(NULL), m_GridSize(0)
457 : {
458 11 : }
459 :
460 11 : LongPathfinder::~LongPathfinder()
461 : {
462 11 : SAFE_DELETE(m_Debug.Overlay);
463 11 : SAFE_DELETE(m_Debug.Grid);
464 11 : SAFE_DELETE(m_Debug.Path);
465 11 : }
466 :
467 7 : void LongPathfinder::SetDebugOverlay(bool enabled)
468 : {
469 7 : if (enabled && !m_Debug.Overlay)
470 : {
471 0 : m_Debug.Overlay = new TerrainTextureOverlay{Pathfinding::NAVCELLS_PER_TERRAIN_TILE,
472 0 : std::bind_front(BuildTextureRGBA, std::ref(*this))};
473 : }
474 7 : else if (!enabled && m_Debug.Overlay)
475 0 : SAFE_DELETE(m_Debug.Overlay);
476 7 : }
477 :
478 : #define PASSABLE(i, j) IS_PASSABLE(state.terrain->get(i, j), state.passClass)
479 :
480 : // Calculate heuristic cost from tile i,j to goal
481 : // (This ought to be an underestimate for correctness)
482 9549 : PathCost LongPathfinder::CalculateHeuristic(int i, int j, int iGoal, int jGoal) const
483 : {
484 9549 : int di = abs(i - iGoal);
485 9549 : int dj = abs(j - jGoal);
486 0 : int diag = std::min(di, dj);
487 9549 : return PathCost(di - diag + dj - diag, diag);
488 : }
489 :
490 : // Do the A* processing for a neighbour tile i,j.
491 8585 : void LongPathfinder::ProcessNeighbour(int pi, int pj, int i, int j, PathCost pg, PathfinderState& state) const
492 : {
493 : // Reject impassable tiles
494 8585 : if (!PASSABLE(i, j))
495 0 : return;
496 :
497 8585 : PathfindTile& n = state.tiles->get(i, j);
498 :
499 8596 : if (n.IsClosed())
500 : return;
501 :
502 8596 : PathCost dg;
503 8596 : if (pi == i)
504 2851 : dg = PathCost::horizvert(abs(pj - j));
505 5745 : else if (pj == j)
506 1908 : dg = PathCost::horizvert(abs(pi - i));
507 : else
508 : {
509 3837 : ASSERT(abs((int)pi - (int)i) == abs((int)pj - (int)j)); // must be 45 degrees
510 3837 : dg = PathCost::diag(abs((int)pi - (int)i));
511 : }
512 :
513 8596 : PathCost g = pg + dg; // cost to this tile = cost to predecessor + delta from predecessor
514 :
515 8596 : PathCost h = CalculateHeuristic(i, j, state.iGoal, state.jGoal);
516 :
517 : // If this is a new tile, compute the heuristic distance
518 8596 : if (n.IsUnexplored())
519 : {
520 : // Remember the best tile we've seen so far, in case we never actually reach the target
521 8596 : if (h < state.hBest)
522 : {
523 2875 : state.hBest = h;
524 2875 : state.iBest = i;
525 2875 : state.jBest = j;
526 : }
527 : }
528 : else
529 : {
530 : // If we've already seen this tile, and the new path to this tile does not have a
531 : // better cost, then stop now
532 0 : if (g >= n.GetCost())
533 : return;
534 :
535 : // Otherwise, we have a better path.
536 :
537 : // If we've already added this tile to the open list:
538 0 : if (n.IsOpen())
539 : {
540 : // This is a better path, so replace the old one with the new cost/parent
541 0 : PathCost gprev = n.GetCost();
542 0 : n.SetCost(g);
543 0 : n.SetPred(pi, pj, i, j);
544 0 : state.open.promote(TileID(i, j), gprev + h, g + h, h);
545 0 : return;
546 : }
547 : }
548 :
549 : // Add it to the open list:
550 8596 : n.SetStatusOpen();
551 8596 : n.SetCost(g);
552 8596 : n.SetPred(pi, pj, i, j);
553 8596 : PriorityQueue::Item t = { TileID(i, j), g + h, h };
554 8596 : state.open.push(t);
555 : }
556 :
557 : /*
558 : * In the JPS algorithm, after a tile is taken off the open queue,
559 : * we don't process every adjacent neighbour (as in standard A*).
560 : * Instead we only move in a subset of directions (depending on the
561 : * direction from the predecessor); and instead of moving by a single
562 : * cell, we move up to the next jump point in that direction.
563 : * The AddJumped... functions do this by calling ProcessNeighbour
564 : * on the jump point (if any) in a certain direction.
565 : * The HasJumped... functions return whether there is any jump point
566 : * in that direction.
567 : */
568 :
569 : // JPS functions scan navcells towards one direction
570 : // OnTheWay tests whether we are scanning towards the right direction, to avoid useless scans
571 1176 : inline bool OnTheWay(int i, int j, int di, int dj, int iGoal, int jGoal)
572 : {
573 1176 : if (dj != 0)
574 : {
575 : // We're not moving towards the goal
576 144 : if ((jGoal - j) * dj < 0)
577 : return false;
578 : }
579 0 : else if (j != jGoal)
580 : return false;
581 :
582 30 : if (di != 0)
583 : {
584 : // We're not moving towards the goal
585 30 : if ((iGoal - i) * di < 0)
586 : return false;
587 : }
588 1032 : else if (i != iGoal)
589 : return false;
590 :
591 : return true;
592 : }
593 :
594 :
595 30 : void LongPathfinder::AddJumpedHoriz(int i, int j, int di, PathCost g, PathfinderState& state, bool detectGoal) const
596 : {
597 30 : if (m_UseJPSCache)
598 : {
599 0 : int jump;
600 0 : if (di > 0)
601 0 : jump = state.jpc->GetJumpPointRight(i, j, state.goal);
602 : else
603 0 : jump = state.jpc->GetJumpPointLeft(i, j, state.goal);
604 :
605 0 : if (jump != i)
606 0 : ProcessNeighbour(i, j, jump, j, g, state);
607 : }
608 : else
609 : {
610 30 : ASSERT(di == 1 || di == -1);
611 30 : int ni = i + di;
612 23286 : while (true)
613 : {
614 11658 : if (!PASSABLE(ni, j))
615 : break;
616 :
617 11628 : if (detectGoal && state.goal.NavcellContainsGoal(ni, j))
618 : {
619 0 : state.open.clear();
620 0 : ProcessNeighbour(i, j, ni, j, g, state);
621 0 : break;
622 : }
623 :
624 11628 : if ((!PASSABLE(ni - di, j - 1) && PASSABLE(ni, j - 1)) ||
625 11628 : (!PASSABLE(ni - di, j + 1) && PASSABLE(ni, j + 1)))
626 : {
627 0 : ProcessNeighbour(i, j, ni, j, g, state);
628 0 : break;
629 : }
630 :
631 11628 : ni += di;
632 : }
633 : }
634 30 : }
635 :
636 : // Returns the i-coordinate of the jump point if it exists, else returns i
637 84 : int LongPathfinder::HasJumpedHoriz(int i, int j, int di, PathfinderState& state, bool detectGoal) const
638 : {
639 84 : if (m_UseJPSCache)
640 : {
641 0 : int jump;
642 0 : if (di > 0)
643 0 : jump = state.jpc->GetJumpPointRight(i, j, state.goal);
644 : else
645 0 : jump = state.jpc->GetJumpPointLeft(i, j, state.goal);
646 :
647 0 : return jump;
648 : }
649 : else
650 : {
651 84 : ASSERT(di == 1 || di == -1);
652 84 : int ni = i + di;
653 61806 : while (true)
654 : {
655 30945 : if (!PASSABLE(ni, j))
656 : return i;
657 :
658 30861 : if (detectGoal && state.goal.NavcellContainsGoal(ni, j))
659 : {
660 0 : state.open.clear();
661 0 : return ni;
662 : }
663 :
664 30861 : if ((!PASSABLE(ni - di, j - 1) && PASSABLE(ni, j - 1)) ||
665 30861 : (!PASSABLE(ni - di, j + 1) && PASSABLE(ni, j + 1)))
666 0 : return ni;
667 :
668 30861 : ni += di;
669 : }
670 : }
671 : }
672 :
673 948 : void LongPathfinder::AddJumpedVert(int i, int j, int dj, PathCost g, PathfinderState& state, bool detectGoal) const
674 : {
675 948 : if (m_UseJPSCache)
676 : {
677 0 : int jump;
678 0 : if (dj > 0)
679 0 : jump = state.jpc->GetJumpPointUp(i, j, state.goal);
680 : else
681 0 : jump = state.jpc->GetJumpPointDown(i, j, state.goal);
682 :
683 0 : if (jump != j)
684 0 : ProcessNeighbour(i, j, i, jump, g, state);
685 : }
686 : else
687 : {
688 948 : ASSERT(dj == 1 || dj == -1);
689 948 : int nj = j + dj;
690 357294 : while (true)
691 : {
692 179121 : if (!PASSABLE(i, nj))
693 : break;
694 :
695 179091 : if (detectGoal && state.goal.NavcellContainsGoal(i, nj))
696 : {
697 918 : state.open.clear();
698 918 : ProcessNeighbour(i, j, i, nj, g, state);
699 918 : break;
700 : }
701 :
702 178173 : if ((!PASSABLE(i - 1, nj - dj) && PASSABLE(i - 1, nj)) ||
703 178173 : (!PASSABLE(i + 1, nj - dj) && PASSABLE(i + 1, nj)))
704 : {
705 0 : ProcessNeighbour(i, j, i, nj, g, state);
706 0 : break;
707 : }
708 :
709 178173 : nj += dj;
710 : }
711 : }
712 948 : }
713 :
714 : // Returns the j-coordinate of the jump point if it exists, else returns j
715 84 : int LongPathfinder::HasJumpedVert(int i, int j, int dj, PathfinderState& state, bool detectGoal) const
716 : {
717 84 : if (m_UseJPSCache)
718 : {
719 0 : int jump;
720 0 : if (dj > 0)
721 0 : jump = state.jpc->GetJumpPointUp(i, j, state.goal);
722 : else
723 0 : jump = state.jpc->GetJumpPointDown(i, j, state.goal);
724 :
725 0 : return jump;
726 : }
727 : else
728 : {
729 84 : ASSERT(dj == 1 || dj == -1);
730 84 : int nj = j + dj;
731 67006 : while (true)
732 : {
733 33545 : if (!PASSABLE(i, nj))
734 : return j;
735 :
736 33491 : if (detectGoal && state.goal.NavcellContainsGoal(i, nj))
737 : {
738 30 : state.open.clear();
739 30 : return nj;
740 : }
741 :
742 33461 : if ((!PASSABLE(i - 1, nj - dj) && PASSABLE(i - 1, nj)) ||
743 33461 : (!PASSABLE(i + 1, nj - dj) && PASSABLE(i + 1, nj)))
744 0 : return nj;
745 :
746 33461 : nj += dj;
747 : }
748 : }
749 : }
750 :
751 : /*
752 : * We never cache diagonal jump points - they're usually so frequent that
753 : * a linear search is about as cheap and avoids the setup cost and memory cost.
754 : */
755 30 : void LongPathfinder::AddJumpedDiag(int i, int j, int di, int dj, PathCost g, PathfinderState& state) const
756 : {
757 : // ProcessNeighbour(i, j, i + di, j + dj, g, state);
758 : // return;
759 :
760 30 : ASSERT(di == 1 || di == -1);
761 30 : ASSERT(dj == 1 || dj == -1);
762 :
763 30 : int ni = i + di;
764 30 : int nj = j + dj;
765 60 : bool detectGoal = OnTheWay(i, j, di, dj, state.iGoal, state.jGoal);
766 138 : while (true)
767 : {
768 : // Stop if we hit an obstructed cell
769 84 : if (!PASSABLE(ni, nj))
770 : return;
771 :
772 : // Stop if moving onto this cell caused us to
773 : // touch the corner of an obstructed cell
774 84 : if (!PASSABLE(ni - di, nj) || !PASSABLE(ni, nj - dj))
775 : return;
776 :
777 : // Process this cell if it's at the goal
778 84 : if (detectGoal && state.goal.NavcellContainsGoal(ni, nj))
779 : {
780 0 : state.open.clear();
781 0 : ProcessNeighbour(i, j, ni, nj, g, state);
782 0 : return;
783 : }
784 :
785 84 : int fi = HasJumpedHoriz(ni, nj, di, state, detectGoal && OnTheWay(ni, nj, di, 0, state.iGoal, state.jGoal));
786 168 : int fj = HasJumpedVert(ni, nj, dj, state, detectGoal && OnTheWay(ni, nj, 0, dj, state.iGoal, state.jGoal));
787 84 : if (fi != ni || fj != nj)
788 : {
789 30 : ProcessNeighbour(i, j, ni, nj, g, state);
790 30 : g += PathCost::diag(abs(ni - i));
791 :
792 30 : if (fi != ni)
793 0 : ProcessNeighbour(ni, nj, fi, nj, g, state);
794 :
795 30 : if (fj != nj)
796 30 : ProcessNeighbour(ni, nj, ni, fj, g, state);
797 :
798 30 : return;
799 : }
800 :
801 54 : ni += di;
802 54 : nj += dj;
803 54 : }
804 : }
805 :
806 954 : void LongPathfinder::ComputeJPSPath(const HierarchicalPathfinder& hierPath, entity_pos_t x0, entity_pos_t z0, const PathGoal& origGoal, pass_class_t passClass, WaypointPath& path) const
807 : {
808 954 : PROFILE2("ComputePathJPS");
809 954 : PathfinderState state = { 0 };
810 :
811 954 : if (m_UseJPSCache)
812 : {
813 : // Needs to lock for construction, or several threads might try doing that at the same time.
814 0 : static std::mutex JPCMutex;
815 0 : std::unique_lock<std::mutex> lock(JPCMutex);
816 0 : std::map<pass_class_t, std::shared_ptr<JumpPointCache>>::const_iterator it = m_JumpPointCache.find(passClass);
817 0 : if (it != m_JumpPointCache.end())
818 0 : state.jpc = it->second.get();
819 :
820 0 : if (!state.jpc)
821 : {
822 0 : m_JumpPointCache[passClass] = std::make_shared<JumpPointCache>();
823 0 : m_JumpPointCache[passClass]->reset(m_Grid, passClass);
824 0 : debug_printf("PATHFINDER: JPC memory: %d kB\n", (int)state.jpc->GetMemoryUsage() / 1024);
825 0 : state.jpc = m_JumpPointCache[passClass].get();
826 : }
827 0 : }
828 :
829 : // Convert the start coordinates to tile indexes
830 954 : std::uint16_t i0, j0;
831 954 : Pathfinding::NearestNavcell(x0, z0, i0, j0, m_GridSize, m_GridSize);
832 :
833 954 : if (!IS_PASSABLE(m_Grid->get(i0, j0), passClass))
834 : {
835 : // The JPS pathfinder requires units to be on passable tiles
836 : // (otherwise it might crash), so handle the supposedly-invalid
837 : // state specially
838 0 : hierPath.FindNearestPassableNavcell(i0, j0, passClass);
839 : }
840 :
841 954 : state.goal = origGoal;
842 :
843 : // Make the goal reachable. This includes shortening the path if the goal is in a non-passable
844 : // region, transforming non-point goals to reachable point goals, etc.
845 954 : hierPath.MakeGoalReachable(i0, j0, state.goal, passClass);
846 :
847 954 : ENSURE(state.goal.type == PathGoal::POINT);
848 :
849 : // If we're already at the goal tile, then move directly to the exact goal coordinates
850 954 : if (state.goal.NavcellContainsGoal(i0, j0))
851 : {
852 0 : path.m_Waypoints.emplace_back(Waypoint{ state.goal.x, state.goal.z });
853 0 : return;
854 : }
855 :
856 954 : Pathfinding::NearestNavcell(state.goal.x, state.goal.z, state.iGoal, state.jGoal, m_GridSize, m_GridSize);
857 :
858 954 : ENSURE((state.goal.x / Pathfinding::NAVCELL_SIZE).ToInt_RoundToNegInfinity() == state.iGoal);
859 954 : ENSURE((state.goal.z / Pathfinding::NAVCELL_SIZE).ToInt_RoundToNegInfinity() == state.jGoal);
860 :
861 954 : state.passClass = passClass;
862 :
863 954 : state.steps = 0;
864 :
865 954 : state.tiles = new PathfindTileGrid(m_Grid->m_W, m_Grid->m_H);
866 953 : state.terrain = m_Grid;
867 :
868 953 : state.iBest = i0;
869 953 : state.jBest = j0;
870 953 : state.hBest = CalculateHeuristic(i0, j0, state.iGoal, state.jGoal);
871 :
872 953 : PriorityQueue::Item start = { TileID(i0, j0), PathCost() };
873 953 : state.open.push(start);
874 954 : state.tiles->get(i0, j0).SetStatusOpen();
875 954 : state.tiles->get(i0, j0).SetPred(i0, j0, i0, j0);
876 954 : state.tiles->get(i0, j0).SetCost(PathCost());
877 :
878 4758 : while (true)
879 : {
880 2856 : ++state.steps;
881 :
882 : // If we ran out of tiles to examine, give up
883 2856 : if (state.open.empty())
884 : break;
885 :
886 : // Move best tile from open to closed
887 2856 : PriorityQueue::Item curr = state.open.pop();
888 2851 : std::uint16_t i = curr.id.i();
889 2851 : std::uint16_t j = curr.id.j();
890 2851 : state.tiles->get(i, j).SetStatusClosed();
891 :
892 : // If we've reached the destination, stop
893 2852 : if (state.goal.NavcellContainsGoal(i, j))
894 : {
895 954 : state.iBest = i;
896 954 : state.jBest = j;
897 954 : state.hBest = PathCost();
898 954 : break;
899 : }
900 :
901 1898 : PathfindTile tile = state.tiles->get(i, j);
902 1902 : PathCost g = tile.GetCost();
903 :
904 : // Get the direction of the predecessor tile from this tile
905 1902 : int dpi = tile.GetPredDI();
906 1902 : int dpj = tile.GetPredDJ();
907 1902 : dpi = (dpi < 0 ? -1 : dpi > 0 ? 1 : 0);
908 1902 : dpj = (dpj < 0 ? -1 : dpj > 0 ? 1 : 0);
909 :
910 1902 : if (dpi != 0 && dpj == 0)
911 : {
912 : // Moving horizontally from predecessor
913 0 : if (!PASSABLE(i + dpi, j - 1))
914 : {
915 0 : AddJumpedDiag(i, j, -dpi, -1, g, state);
916 0 : AddJumpedVert(i, j, -1, g, state, OnTheWay(i, j, 0, -1, state.iGoal, state.jGoal));
917 : }
918 0 : if (!PASSABLE(i + dpi, j + 1))
919 : {
920 0 : AddJumpedDiag(i, j, -dpi, +1, g, state);
921 0 : AddJumpedVert(i, j, +1, g, state, OnTheWay(i, j, 0, +1, state.iGoal, state.jGoal));
922 : }
923 0 : AddJumpedHoriz(i, j, -dpi, g, state, OnTheWay(i, j, -dpi, 0, state.iGoal, state.jGoal));
924 : }
925 1902 : else if (dpi == 0 && dpj != 0)
926 : {
927 : // Moving vertically from predecessor
928 918 : if (!PASSABLE(i - 1, j + dpj))
929 : {
930 0 : AddJumpedDiag(i, j, -1, -dpj, g, state);
931 0 : AddJumpedHoriz(i, j, -1, g, state,OnTheWay(i, j, -1, 0, state.iGoal, state.jGoal));
932 : }
933 918 : if (!PASSABLE(i + 1, j + dpj))
934 : {
935 0 : AddJumpedDiag(i, j, +1, -dpj, g, state);
936 0 : AddJumpedHoriz(i, j, +1, g, state,OnTheWay(i, j, +1, 0, state.iGoal, state.jGoal));
937 : }
938 1836 : AddJumpedVert(i, j, -dpj, g, state, OnTheWay(i, j, 0, -dpj, state.iGoal, state.jGoal));
939 : }
940 984 : else if (dpi != 0 && dpj != 0)
941 : {
942 : // Moving diagonally from predecessor
943 30 : AddJumpedHoriz(i, j, -dpi, g, state, OnTheWay(i, j, -dpi, 0, state.iGoal, state.jGoal));
944 60 : AddJumpedVert(i, j, -dpj, g, state, OnTheWay(i, j, 0, -dpj, state.iGoal, state.jGoal));
945 30 : AddJumpedDiag(i, j, -dpi, -dpj, g, state);
946 : }
947 : else
948 : {
949 : // No predecessor, i.e. the start tile
950 : // Start searching in every direction
951 :
952 : // XXX - check passability?
953 :
954 954 : bool passl = PASSABLE(i - 1, j);
955 954 : bool passr = PASSABLE(i + 1, j);
956 954 : bool passd = PASSABLE(i, j - 1);
957 954 : bool passu = PASSABLE(i, j + 1);
958 :
959 954 : if (passl && passd)
960 954 : ProcessNeighbour(i, j, i-1, j-1, g, state);
961 954 : if (passr && passd)
962 954 : ProcessNeighbour(i, j, i+1, j-1, g, state);
963 953 : if (passl && passu)
964 953 : ProcessNeighbour(i, j, i-1, j+1, g, state);
965 953 : if (passr && passu)
966 953 : ProcessNeighbour(i, j, i+1, j+1, g, state);
967 954 : if (passl)
968 954 : ProcessNeighbour(i, j, i-1, j, g, state);
969 954 : if (passr)
970 954 : ProcessNeighbour(i, j, i+1, j, g, state);
971 954 : if (passd)
972 954 : ProcessNeighbour(i, j, i, j-1, g, state);
973 954 : if (passu)
974 954 : ProcessNeighbour(i, j, i, j+1, g, state);
975 : }
976 1902 : }
977 :
978 : // Reconstruct the path (in reverse)
979 954 : std::uint16_t ip = state.iBest, jp = state.jBest;
980 2882 : while (ip != i0 || jp != j0)
981 : {
982 1929 : PathfindTile& n = state.tiles->get(ip, jp);
983 1932 : entity_pos_t x, z;
984 1932 : Pathfinding::NavcellCenter(ip, jp, x, z);
985 1932 : path.m_Waypoints.emplace_back(Waypoint{ x, z });
986 :
987 : // Follow the predecessor link
988 1928 : ip = n.GetPredI(ip);
989 1928 : jp = n.GetPredJ(jp);
990 : }
991 : // The last waypoint is slightly incorrect (it's not the goal but the center
992 : // of the navcell of the goal), so replace it
993 953 : if (!path.m_Waypoints.empty())
994 953 : path.m_Waypoints.front() = { state.goal.x, state.goal.z };
995 :
996 953 : ImprovePathWaypoints(path, passClass, origGoal.maxdist, x0, z0);
997 :
998 : // Save this grid for debug display
999 954 : if (m_Debug.Overlay)
1000 : {
1001 0 : std::lock_guard<std::mutex> lock(g_DebugMutex);
1002 0 : delete m_Debug.Grid;
1003 0 : m_Debug.Grid = state.tiles;
1004 0 : m_Debug.Steps = state.steps;
1005 0 : m_Debug.Goal = state.goal;
1006 0 : }
1007 : else
1008 954 : SAFE_DELETE(state.tiles);
1009 953 : }
1010 :
1011 : #undef PASSABLE
1012 :
1013 953 : void LongPathfinder::ImprovePathWaypoints(WaypointPath& path, pass_class_t passClass, entity_pos_t maxDist, entity_pos_t x0, entity_pos_t z0) const
1014 : {
1015 953 : if (path.m_Waypoints.empty())
1016 6 : return;
1017 :
1018 953 : if (maxDist > fixed::Zero())
1019 : {
1020 953 : CFixedVector2D start(x0, z0);
1021 953 : CFixedVector2D first(path.m_Waypoints.back().x, path.m_Waypoints.back().z);
1022 953 : CFixedVector2D offset = first - start;
1023 953 : if (offset.CompareLength(maxDist) > 0)
1024 : {
1025 0 : offset.Normalize(maxDist);
1026 0 : path.m_Waypoints.emplace_back(Waypoint{ (start + offset).X, (start + offset).Y });
1027 : }
1028 : }
1029 :
1030 953 : if (path.m_Waypoints.size() < 2)
1031 : return;
1032 :
1033 947 : std::vector<Waypoint>& waypoints = path.m_Waypoints;
1034 947 : std::vector<Waypoint> newWaypoints;
1035 :
1036 947 : CFixedVector2D prev(waypoints.front().x, waypoints.front().z);
1037 947 : newWaypoints.push_back(waypoints.front());
1038 978 : for (size_t k = 1; k < waypoints.size() - 1; ++k)
1039 : {
1040 30 : CFixedVector2D ahead(waypoints[k + 1].x, waypoints[k + 1].z);
1041 30 : CFixedVector2D curr(waypoints[k].x, waypoints[k].z);
1042 :
1043 30 : if (maxDist > fixed::Zero() && (curr - prev).CompareLength(maxDist) > 0)
1044 : {
1045 : // We are too far away from the previous waypoint, so create one in
1046 : // between and continue with the improvement of the path
1047 0 : prev = prev + (curr - prev) / 2;
1048 0 : newWaypoints.emplace_back(Waypoint{ prev.X, prev.Y });
1049 : }
1050 :
1051 : // If we're mostly straight, don't even bother.
1052 30 : if ((ahead - curr).Perpendicular().Dot(curr - prev).Absolute() <= fixed::Epsilon() * 100)
1053 0 : continue;
1054 :
1055 30 : if (!Pathfinding::CheckLineMovement(prev.X, prev.Y, ahead.X, ahead.Y, passClass, *m_Grid))
1056 : {
1057 0 : prev = CFixedVector2D(waypoints[k].x, waypoints[k].z);
1058 0 : newWaypoints.push_back(waypoints[k]);
1059 : }
1060 : }
1061 948 : newWaypoints.push_back(waypoints.back());
1062 948 : path.m_Waypoints.swap(newWaypoints);
1063 948 : }
1064 :
1065 0 : void LongPathfinder::GetDebugDataJPS(std::uint32_t& steps, double& time, Grid<std::uint8_t>& grid) const
1066 : {
1067 0 : steps = m_Debug.Steps;
1068 0 : time = m_Debug.Time;
1069 :
1070 0 : if (!m_Debug.Grid)
1071 0 : return;
1072 :
1073 0 : std::lock_guard<std::mutex> lock(g_DebugMutex);
1074 :
1075 0 : std::uint16_t iGoal, jGoal;
1076 0 : Pathfinding::NearestNavcell(m_Debug.Goal.x, m_Debug.Goal.z, iGoal, jGoal, m_GridSize, m_GridSize);
1077 :
1078 0 : grid = Grid<std::uint8_t>(m_Debug.Grid->m_W, m_Debug.Grid->m_H);
1079 0 : for (std::uint16_t j = 0; j < grid.m_H; ++j)
1080 : {
1081 0 : for (std::uint16_t i = 0; i < grid.m_W; ++i)
1082 : {
1083 0 : if (i == iGoal && j == jGoal)
1084 0 : continue;
1085 0 : PathfindTile t = m_Debug.Grid->get(i, j);
1086 0 : grid.set(i, j, (t.IsOpen() ? 1 : 0) | (t.IsClosed() ? 2 : 0));
1087 : }
1088 : }
1089 0 : }
1090 :
1091 954 : void LongPathfinder::ComputePath(const HierarchicalPathfinder& hierPath, entity_pos_t x0, entity_pos_t z0, const PathGoal& origGoal,
1092 : pass_class_t passClass, WaypointPath& path) const
1093 : {
1094 954 : if (!m_Grid)
1095 : {
1096 0 : LOGERROR("The pathfinder grid hasn't been setup yet, aborting ComputeJPSPath");
1097 0 : return;
1098 : }
1099 :
1100 954 : ComputeJPSPath(hierPath, x0, z0, origGoal, passClass, path);
1101 : }
1102 0 : void LongPathfinder::ComputePath(const HierarchicalPathfinder& hierPath, entity_pos_t x0, entity_pos_t z0, const PathGoal& origGoal,
1103 : pass_class_t passClass, std::vector<CircularRegion> excludedRegions, WaypointPath& path)
1104 : {
1105 0 : GenerateSpecialMap(passClass, excludedRegions);
1106 0 : ComputeJPSPath(hierPath, x0, z0, origGoal, SPECIAL_PASS_CLASS, path);
1107 0 : }
1108 :
1109 0 : inline bool InRegion(std::uint16_t i, std::uint16_t j, CircularRegion region)
1110 : {
1111 0 : fixed cellX = Pathfinding::NAVCELL_SIZE * i;
1112 0 : fixed cellZ = Pathfinding::NAVCELL_SIZE * j;
1113 :
1114 0 : return CFixedVector2D(cellX - region.x, cellZ - region.z).CompareLength(region.r) <= 0;
1115 : }
1116 :
1117 0 : void LongPathfinder::GenerateSpecialMap(pass_class_t passClass, std::vector<CircularRegion> excludedRegions)
1118 : {
1119 0 : for (std::uint16_t j = 0; j < m_Grid->m_H; ++j)
1120 : {
1121 0 : for (std::uint16_t i = 0; i < m_Grid->m_W; ++i)
1122 : {
1123 0 : NavcellData n = m_Grid->get(i, j);
1124 0 : if (!IS_PASSABLE(n, passClass))
1125 : {
1126 0 : n |= SPECIAL_PASS_CLASS;
1127 0 : m_Grid->set(i, j, n);
1128 0 : continue;
1129 : }
1130 :
1131 0 : for (CircularRegion& region : excludedRegions)
1132 : {
1133 0 : if (!InRegion(i, j, region))
1134 0 : continue;
1135 :
1136 0 : n |= SPECIAL_PASS_CLASS;
1137 0 : break;
1138 : }
1139 0 : m_Grid->set(i, j, n);
1140 : }
1141 : }
1142 0 : }
|