Skip to content

Commit f584408

Browse files
snow-jallenclaude
andcommitted
Pathfinding: same paths, a tenth of the work in big battles
A load test on prod (four 16-Formics matches) fell behind at 250 ms ticks, and a profile put 77% of the CPU in Pathfinder.FindPath. Most of it was units that can't get any closer to their goal (an attack-move onto a building tile, re-sent by the bot every tick) searching their whole reachable map again each tick. - PathSearch: one per match, reusing its arrays (a search costs what it explores, not the map's size). - Regions: the map's connected areas, relabeled when a building or deposit comes or goes. A unit can get closer exactly when some tile in its region is nearer the goal, so a stuck unit is a lookup, not a search, and a search for an unreachable goal stops at the first tile as near as the region gets. - GameSimulation keeps a blocked-tile grid, written only through SetBuildingAt/SetDepositAt. Every path is the same as before: the bot characterization hashes and replay tests are unchanged, and PathSearchTests checks 9,000 random searches (walled-off goals included) against the old A*. One 16-Formics match, simulation per tick at its worst: classic 172 -> 17 ms, spring 70 -> 9 ms (locally). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01V8fdNFMnkyDNTFoKqQyD6L
1 parent eed03e0 commit f584408

5 files changed

Lines changed: 313 additions & 41 deletions

File tree

‎src/NetRts.Engine/GameSimulation.Testing.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ internal int SpawnDeposit(int x, int y, int amount)
1515
var deposit = new DepositEntity(_nextEntityId++, new Point(x, y), amount);
1616
_deposits.Add(deposit);
1717
_entities[deposit.Id] = deposit;
18-
_depositAt[Index(deposit.Position)] = deposit.Id;
18+
SetDepositAt(deposit.Position, deposit.Id);
1919
return deposit.Id;
2020
}
2121

@@ -42,7 +42,7 @@ internal void RemoveEntity(int entityId)
4242
_buildings.RemoveAll(b => b.Id == entityId);
4343
if (entity is BuildingEntity)
4444
{
45-
_buildingAt[Index(entity.Position)] = 0;
45+
SetBuildingAt(entity.Position, 0);
4646
}
4747

4848
_entities.Remove(entityId);

‎src/NetRts.Engine/GameSimulation.Tick.cs‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -507,7 +507,9 @@ private StepResult StepToward(UnitEntity unit, Point goal, int range)
507507
|| !Passable(unit.Path[0]);
508508
if (needsPath)
509509
{
510-
unit.Path = Pathfinder.FindPath(Map.Width, Map.Height, Passable, unit.Position, goal, range);
510+
// A unit already as close as it can get (its goal walled off, and a bot sending the same order
511+
// every tick) would otherwise search everywhere it can reach, every tick, to find that out.
512+
unit.Path = _paths.CanGetCloser(unit.Position, goal, range) ? _paths.Find(unit.Position, goal, range) : [];
511513
unit.PathGoal = goal;
512514
unit.PathRange = range;
513515
if (unit.Path.Count == 0)
@@ -645,7 +647,7 @@ private void Dig(UnitEntity unit, PlayerState player, Entity source)
645647
{
646648
_deposits.Remove(deposit);
647649
_entities.Remove(deposit.Id);
648-
_depositAt[Index(deposit.Position)] = 0;
650+
SetDepositAt(deposit.Position, 0);
649651
player.DepositsExhausted++;
650652
AddEvent(player, "DepositDepleted", $"Deposit {deposit.Id} at {deposit.Position} is exhausted", deposit.Id);
651653
}
@@ -802,7 +804,7 @@ private void RemoveDead(Dictionary<int, Attack> killers)
802804
{
803805
_buildings.Remove(building);
804806
_entities.Remove(building.Id);
805-
_buildingAt[Index(building.Position)] = 0;
807+
SetBuildingAt(building.Position, 0);
806808
var owner = _players[building.Owner];
807809
owner.BuildingsLost++;
808810
AddEvent(owner, "BuildingLost", $"{building.Type} {building.Id} was destroyed at {building.Position}", building.Id, spectator: false);
@@ -838,7 +840,7 @@ private void Eliminate(PlayerState player, string reason)
838840
{
839841
_buildings.Remove(building);
840842
_entities.Remove(building.Id);
841-
_buildingAt[Index(building.Position)] = 0;
843+
SetBuildingAt(building.Position, 0);
842844
}
843845

844846
var message = $"{player.Name} {reason}";

‎src/NetRts.Engine/GameSimulation.cs‎

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ public sealed partial class GameSimulation
6565
private readonly Dictionary<int, Entity> _entities = [];
6666
private readonly int[] _buildingAt;
6767
private readonly int[] _depositAt;
68+
private readonly bool[] _blocked; // rock, a building or a deposit: what units can't walk through
69+
private readonly PathSearch _paths;
6870
private readonly List<GameEventDto> _spectatorEvents = [];
6971
private readonly List<ReplayCommandDto> _replayCommands = [];
7072
private readonly List<ReplaySurrenderDto> _replaySurrenders = [];
@@ -101,13 +103,20 @@ public GameSimulation(Guid matchId, GameConfig config, IReadOnlyList<PlayerSeat>
101103
_buildingAt = new int[Map.Width * Map.Height];
102104
_depositAt = new int[Map.Width * Map.Height];
103105
_cellLoad = new int[Map.Width * Map.Height];
106+
_blocked = new bool[Map.Width * Map.Height];
107+
for (var i = 0; i < _blocked.Length; i++)
108+
{
109+
_blocked[i] = Map.IsRock(i % Map.Width, i / Map.Width);
110+
}
111+
112+
_paths = new PathSearch(Map.Width, Map.Height, _blocked);
104113

105114
foreach (var spawn in Map.Deposits)
106115
{
107116
var deposit = new DepositEntity(_nextEntityId++, spawn.Position, spawn.Amount);
108117
_deposits.Add(deposit);
109118
_entities[deposit.Id] = deposit;
110-
_depositAt[Index(spawn.Position)] = deposit.Id;
119+
SetDepositAt(spawn.Position, deposit.Id);
111120
}
112121

113122
for (var slot = 0; slot < seats.Count; slot++)
@@ -404,15 +413,31 @@ private long Enqueue(int slot, CommandRequest request, bool boosted = false)
404413

405414
private int Index(Point p) => p.Y * Map.Width + p.X;
406415

407-
private bool Passable(int x, int y)
416+
private bool Passable(int x, int y) => Map.InBounds(x, y) && !_blocked[y * Map.Width + x];
417+
418+
/// <summary>Puts a building on a tile, or clears it (id 0).</summary>
419+
private void SetBuildingAt(Point p, int id)
408420
{
409-
if (!Map.InBounds(x, y) || Map.IsRock(x, y))
421+
_buildingAt[Index(p)] = id;
422+
Reblock(p);
423+
}
424+
425+
/// <summary>Puts a deposit on a tile, or clears it (id 0).</summary>
426+
private void SetDepositAt(Point p, int id)
427+
{
428+
_depositAt[Index(p)] = id;
429+
Reblock(p);
430+
}
431+
432+
private void Reblock(Point p)
433+
{
434+
var i = Index(p);
435+
var blocked = Map.IsRock(p) || _buildingAt[i] != 0 || _depositAt[i] != 0;
436+
if (blocked != _blocked[i])
410437
{
411-
return false;
438+
_blocked[i] = blocked;
439+
_paths.BlockedChanged();
412440
}
413-
414-
var i = y * Map.Width + x;
415-
return _buildingAt[i] == 0 && _depositAt[i] == 0;
416441
}
417442

418443
private bool Passable(Point p) => Passable(p.X, p.Y);
@@ -435,7 +460,7 @@ private BuildingEntity AddBuilding(int owner, BuildingType type, Point position,
435460
var building = new BuildingEntity(_nextEntityId++, owner, type, Rules.Buildings[type], position, completed);
436461
_buildings.Add(building);
437462
_entities[building.Id] = building;
438-
_buildingAt[Index(position)] = building.Id;
463+
SetBuildingAt(position, building.Id);
439464
if (completed)
440465
{
441466
Planted(building);

‎src/NetRts.Engine/Pathfinder.cs‎

Lines changed: 152 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
namespace NetRts.Engine;
22

33
/// <summary>
4-
/// 8-directional A* over the tile grid. Diagonal steps cost the same as straight ones
5-
/// (Chebyshev metric) but may not cut the corner of a blocked tile.
4+
/// How units move over the tile grid: in 8 directions, diagonal steps costing the same as straight ones
5+
/// (Chebyshev metric) but never cutting the corner of a blocked tile. <see cref="PathSearch"/> plans routes.
66
/// </summary>
77
internal static class Pathfinder
88
{
9-
private static readonly (int Dx, int Dy)[] Directions =
9+
internal static readonly (int Dx, int Dy)[] Directions =
1010
[
1111
(0, -1), (1, 0), (0, 1), (-1, 0),
1212
(1, -1), (1, 1), (-1, 1), (-1, -1),
@@ -31,49 +31,167 @@ public static IEnumerable<Point> Neighbors(Point p, Func<int, int, bool> passabl
3131
yield return new Point(nx, ny);
3232
}
3333
}
34+
}
35+
36+
/// <summary>
37+
/// One match's A* searches over its grid of blocked tiles (call <see cref="BlockedChanged"/> when it changes).
38+
/// The working arrays are reused from search to search, so a short search costs what it explores, not the
39+
/// size of the map.
40+
/// </summary>
41+
internal sealed class PathSearch(int width, int height, bool[] blocked)
42+
{
43+
private readonly int[] _cost = new int[width * height];
44+
private readonly int[] _cameFrom = new int[width * height];
45+
private readonly int[] _seen = new int[width * height]; // the search that last touched each tile; _cost is stale otherwise
46+
private readonly PriorityQueue<int, (int F, int H, int Seq)> _open = new();
47+
private int _search;
48+
49+
// Regions: which tiles can reach which (-1 for blocked ones).
50+
private readonly int[] _region = new int[width * height];
51+
private readonly Queue<int> _fill = new();
52+
private bool _regionsStale = true;
53+
54+
private bool Passable(int x, int y) => (uint)x < (uint)width && (uint)y < (uint)height && !blocked[y * width + x];
55+
56+
private int CostAt(int i) => _seen[i] == _search ? _cost[i] : int.MaxValue;
57+
58+
private static int Heuristic(int x, int y, Point target, int range) =>
59+
Math.Max(0, Math.Max(Math.Abs(x - target.X), Math.Abs(y - target.Y)) - range);
60+
61+
public void BlockedChanged() => _regionsStale = true;
62+
63+
/// <summary>
64+
/// Whether any tile reachable from <paramref name="start"/> is nearer the goal than it is: exactly when
65+
/// <see cref="Find"/> returns a path, since the search ends on the nearest tile it reaches and the start
66+
/// wins a tie. Much cheaper than finding out by searching. A start on a blocked tile has no region, so
67+
/// the answer there is yes: search and see.
68+
/// </summary>
69+
public bool CanGetCloser(Point start, Point target, int range) =>
70+
Heuristic(start.X, start.Y, target, range) > (Nearest(start, target, range) ?? 0);
71+
72+
/// <summary>
73+
/// How near the goal (in <see cref="Heuristic"/> terms: 0 is within range) the nearest tile reachable from
74+
/// <paramref name="start"/> is; null when <paramref name="start"/> is blocked and so has no region.
75+
/// </summary>
76+
private int? Nearest(Point start, Point target, int range)
77+
{
78+
var s = start.Y * width + start.X;
79+
if (blocked[s])
80+
{
81+
return null;
82+
}
83+
84+
if (_regionsStale)
85+
{
86+
Relabel();
87+
}
88+
89+
// Ring by ring out from the target: the first ring with a tile of the start's region is the nearest.
90+
// The start's own ring has one, so this ends.
91+
var region = _region[s];
92+
for (var r = 0; ; r++)
93+
{
94+
for (var d = -r; d <= r; d++)
95+
{
96+
if (InRegion(target.X + d, target.Y - r, region) || InRegion(target.X + d, target.Y + r, region)
97+
|| InRegion(target.X - r, target.Y + d, region) || InRegion(target.X + r, target.Y + d, region))
98+
{
99+
return Math.Max(0, r - range);
100+
}
101+
}
102+
}
103+
}
104+
105+
private bool InRegion(int x, int y, int region) =>
106+
(uint)x < (uint)width && (uint)y < (uint)height && _region[y * width + x] == region;
107+
108+
/// <summary>Flood-fills the regions, moving the way <see cref="Find"/> does.</summary>
109+
private void Relabel()
110+
{
111+
Array.Fill(_region, -1);
112+
var next = 0;
113+
for (var first = 0; first < _region.Length; first++)
114+
{
115+
if (blocked[first] || _region[first] >= 0)
116+
{
117+
continue;
118+
}
119+
120+
_region[first] = next;
121+
_fill.Enqueue(first);
122+
while (_fill.TryDequeue(out var current))
123+
{
124+
var (x, y) = (current % width, current / width);
125+
foreach (var (dx, dy) in Pathfinder.Directions)
126+
{
127+
var n = (y + dy) * width + x + dx;
128+
if (CanStep(x, y, dx, dy) && _region[n] < 0)
129+
{
130+
_region[n] = next;
131+
_fill.Enqueue(n);
132+
}
133+
}
134+
}
135+
136+
next++;
137+
}
138+
139+
_regionsStale = false;
140+
}
141+
142+
/// <summary>Pathfinder.Neighbors' rule: onto a passable tile, without cutting the corner of a blocked one.</summary>
143+
private bool CanStep(int x, int y, int dx, int dy) =>
144+
Passable(x + dx, y + dy) && (dx == 0 || dy == 0 || (Passable(x + dx, y) && Passable(x, y + dy)));
34145

35146
/// <summary>
36147
/// Finds a path from <paramref name="start"/> to any passable tile within Chebyshev
37148
/// <paramref name="range"/> of <paramref name="target"/>. If no such tile is reachable the
38149
/// path leads to the reachable tile closest to the target. The start tile is not included;
39150
/// an empty list means "already as close as possible".
40151
/// </summary>
41-
public static List<Point> FindPath(int width, int height, Func<int, int, bool> passable, Point start, Point target, int range)
152+
public List<Point> Find(Point start, Point target, int range)
42153
{
43-
int Heuristic(Point p) => Math.Max(0, p.Chebyshev(target) - range);
154+
int Heuristic(int x, int y) => PathSearch.Heuristic(x, y, target, range);
44155

45-
if (Heuristic(start) == 0)
156+
if (Heuristic(start.X, start.Y) == 0)
46157
{
47158
return [];
48159
}
49160

50-
var size = width * height;
51-
var cameFrom = new int[size];
52-
var cost = new int[size];
53-
Array.Fill(cost, int.MaxValue);
54-
Array.Fill(cameFrom, -1);
161+
// Tiles come off the queue nearest-first by cost so far plus distance left, so the first one as near as
162+
// this region gets is the one the search would end on anyway: stop there rather than search it all.
163+
var nearest = Nearest(start, target, range) ?? 0;
164+
165+
if (++_search == int.MaxValue)
166+
{
167+
Array.Clear(_seen);
168+
_search = 1;
169+
}
55170

171+
var size = width * height;
56172
var startIndex = start.Y * width + start.X;
57-
cost[startIndex] = 0;
173+
_seen[startIndex] = _search;
174+
_cost[startIndex] = 0;
58175

59-
var open = new PriorityQueue<int, (int F, int H, int Seq)>();
176+
_open.Clear();
60177
var seq = 0;
61-
open.Enqueue(startIndex, (Heuristic(start), Heuristic(start), seq++));
178+
var startH = Heuristic(start.X, start.Y);
179+
_open.Enqueue(startIndex, (startH, startH, seq++));
62180

63181
var bestIndex = startIndex;
64-
var bestH = Heuristic(start);
182+
var bestH = startH;
65183
var bestCost = 0;
66184
var expansions = 0;
67185

68-
while (open.TryDequeue(out var current, out var priority))
186+
while (_open.TryDequeue(out var current, out var priority))
69187
{
70-
var g = cost[current];
188+
var g = _cost[current];
71189
if (priority.F - priority.H != g)
72190
{
73191
continue; // stale queue entry
74192
}
75193

76-
var p = new Point(current % width, current / width);
194+
var (x, y) = (current % width, current / width);
77195
var h = priority.H;
78196
if (h < bestH || (h == bestH && g < bestCost))
79197
{
@@ -82,29 +200,36 @@ public static List<Point> FindPath(int width, int height, Func<int, int, bool> p
82200
bestCost = g;
83201
}
84202

85-
if (h == 0 || ++expansions > size)
203+
if (h <= nearest || ++expansions > size)
86204
{
87205
break;
88206
}
89207

90-
foreach (var n in Neighbors(p, passable))
208+
foreach (var (dx, dy) in Pathfinder.Directions) // Pathfinder.Neighbors' order
91209
{
92-
var ni = n.Y * width + n.X;
210+
var (nx, ny) = (x + dx, y + dy);
211+
if (!CanStep(x, y, dx, dy))
212+
{
213+
continue;
214+
}
215+
216+
var ni = ny * width + nx;
93217
var ng = g + 1;
94-
if (ng >= cost[ni])
218+
if (ng >= CostAt(ni))
95219
{
96220
continue;
97221
}
98222

99-
cost[ni] = ng;
100-
cameFrom[ni] = current;
101-
var nh = Heuristic(n);
102-
open.Enqueue(ni, (ng + nh, nh, seq++));
223+
_seen[ni] = _search;
224+
_cost[ni] = ng;
225+
_cameFrom[ni] = current;
226+
var nh = Heuristic(nx, ny);
227+
_open.Enqueue(ni, (ng + nh, nh, seq++));
103228
}
104229
}
105230

106231
var path = new List<Point>();
107-
for (var i = bestIndex; i != startIndex; i = cameFrom[i])
232+
for (var i = bestIndex; i != startIndex; i = _cameFrom[i])
108233
{
109234
path.Add(new Point(i % width, i / width));
110235
}

0 commit comments

Comments
 (0)