@codexo/exojs-pathfinding 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +172 -0
- package/dist/esm/Pathfinder.d.ts +50 -0
- package/dist/esm/Pathfinder.d.ts.map +1 -0
- package/dist/esm/Pathfinder.js +151 -0
- package/dist/esm/Pathfinder.js.map +1 -0
- package/dist/esm/core/BinaryHeap.d.ts +2 -0
- package/dist/esm/core/BinaryHeap.d.ts.map +1 -0
- package/dist/esm/core/BinaryHeap.js +90 -0
- package/dist/esm/core/BinaryHeap.js.map +1 -0
- package/dist/esm/core/SearchState.d.ts +2 -0
- package/dist/esm/core/SearchState.d.ts.map +1 -0
- package/dist/esm/core/SearchState.js +66 -0
- package/dist/esm/core/SearchState.js.map +1 -0
- package/dist/esm/core/search.d.ts +2 -0
- package/dist/esm/core/search.d.ts.map +1 -0
- package/dist/esm/core/search.js +106 -0
- package/dist/esm/core/search.js.map +1 -0
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +5 -0
- package/dist/esm/public.d.ts +7 -0
- package/dist/esm/public.d.ts.map +1 -0
- package/dist/esm/spaces/GridJumpExpansion.d.ts +2 -0
- package/dist/esm/spaces/GridJumpExpansion.d.ts.map +1 -0
- package/dist/esm/spaces/GridJumpExpansion.js +137 -0
- package/dist/esm/spaces/GridJumpExpansion.js.map +1 -0
- package/dist/esm/spaces/GridSpace.d.ts +131 -0
- package/dist/esm/spaces/GridSpace.d.ts.map +1 -0
- package/dist/esm/spaces/GridSpace.js +296 -0
- package/dist/esm/spaces/GridSpace.js.map +1 -0
- package/dist/esm/spaces/WaypointGraph.d.ts +79 -0
- package/dist/esm/spaces/WaypointGraph.d.ts.map +1 -0
- package/dist/esm/spaces/WaypointGraph.js +167 -0
- package/dist/esm/spaces/WaypointGraph.js.map +1 -0
- package/dist/esm/spaces/gridGeometry.d.ts +3 -0
- package/dist/esm/spaces/gridGeometry.d.ts.map +1 -0
- package/dist/esm/spaces/gridGeometry.js +40 -0
- package/dist/esm/spaces/gridGeometry.js.map +1 -0
- package/dist/esm/types.d.ts +182 -0
- package/dist/esm/types.d.ts.map +1 -0
- package/package.json +46 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Codexo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
# @codexo/exojs-pathfinding
|
|
2
|
+
|
|
3
|
+
Official ExoJS extension for 2D pathfinding. One search core - A\* with jump-point pruning -
|
|
4
|
+
over pluggable navigation spaces: weighted grids for top-down worlds, waypoint graphs for
|
|
5
|
+
platformers and for graphs that have no geometry at all.
|
|
6
|
+
|
|
7
|
+
It is plain logic. No scene node, no renderer, no asset type, no registration step: you
|
|
8
|
+
construct a space and a `Pathfinder`, and you own both.
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @codexo/exojs @codexo/exojs-pathfinding
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
`@codexo/exojs` is a peer dependency and the only one. In particular this package does **not**
|
|
17
|
+
depend on `@codexo/exojs-tilemap`: feeding a tilemap into a grid is three lines of your code,
|
|
18
|
+
shown below.
|
|
19
|
+
|
|
20
|
+
## What this package provides
|
|
21
|
+
|
|
22
|
+
- `Pathfinder` - runs the queries and owns the reusable search buffers.
|
|
23
|
+
- `GridSpace` - a finite window of weighted cells, with diagonal policies, per-cell costs,
|
|
24
|
+
clearance for wide agents, string-pulling path smoothing, and a jump-point fast path.
|
|
25
|
+
- `WaypointGraph` - a directed graph of hand-placed nodes whose edges carry a `kind` and a
|
|
26
|
+
payload, so a path can tell a jump from a walk.
|
|
27
|
+
- `NavigationSpace` - the interface both implement, and the one your own space implements when
|
|
28
|
+
neither fits.
|
|
29
|
+
|
|
30
|
+
## Capability matrix
|
|
31
|
+
|
|
32
|
+
| Capability | `GridSpace` | `WaypointGraph` |
|
|
33
|
+
| ----------------------------------- | ------------------------------------------- | -------------------------------- |
|
|
34
|
+
| Per-step costs | per cell, `0` blocks | per edge |
|
|
35
|
+
| Heuristic | octile / Manhattan, scaled by cheapest cell | straight-line distance |
|
|
36
|
+
| Directed traversal | no - movement is symmetric | yes |
|
|
37
|
+
| Traversal kinds (`walk`/`jump`/...) | no | yes, with an arbitrary payload |
|
|
38
|
+
| Positionless (pure Dijkstra) | no | yes, when a node has no position |
|
|
39
|
+
| Clearance / wide agents | yes, `agentSize` | no |
|
|
40
|
+
| Path smoothing | yes, string pulling | no |
|
|
41
|
+
| Jump-point pruning | yes, on a uniform-cost grid | no |
|
|
42
|
+
| Mutable at runtime | `setCost` | `addNode`/`addEdge`/`remove*` |
|
|
43
|
+
|
|
44
|
+
## Usage
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import { GridSpace, Pathfinder } from '@codexo/exojs-pathfinding';
|
|
48
|
+
|
|
49
|
+
const grid = GridSpace.from(64, 64, (x, y) => (isWall(x, y) ? 0 : terrainCost(x, y)), {
|
|
50
|
+
cellSize: 32,
|
|
51
|
+
});
|
|
52
|
+
const pathfinder = new Pathfinder();
|
|
53
|
+
|
|
54
|
+
const result = pathfinder.findPathBetween(grid, hero.x, hero.y, target.x, target.y, {
|
|
55
|
+
smooth: true,
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
if (result.status === 'found') {
|
|
59
|
+
hero.follow(result.points);
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`findPath` takes node ids, `findPathBetween` takes world coordinates. Both return the same
|
|
64
|
+
`PathResult`, and `status` is a value rather than an exception, because "no path" is an ordinary
|
|
65
|
+
game state:
|
|
66
|
+
|
|
67
|
+
| `status` | Meaning |
|
|
68
|
+
| ----------------- | -------------------------------------------------------------------- |
|
|
69
|
+
| `found` | Complete, cost-optimal path. |
|
|
70
|
+
| `unreachable` | The search exhausted the space. Empty path, unless `snapToNearest`. |
|
|
71
|
+
| `budget-exceeded` | `maxExpandedNodes` ran out. The best partial path is still returned. |
|
|
72
|
+
|
|
73
|
+
`result.revision` records `space.revision` at search time, so a follower can notice that the
|
|
74
|
+
world changed under its path and ask for a new one.
|
|
75
|
+
|
|
76
|
+
## Grids
|
|
77
|
+
|
|
78
|
+
Coordinates are absolute cell coordinates - the same numbers your map uses - not offsets into
|
|
79
|
+
the window. The window itself is finite by construction, and everything outside it is blocked;
|
|
80
|
+
that is the answer for infinite or streamed maps: size the window to the region the actors are
|
|
81
|
+
in, and push chunk changes into it with `setCost`.
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
// Streamed tilemap, no package dependency in either direction.
|
|
85
|
+
const window = GridSpace.from(96, 96, (x, y) => walkCost(map.getTileAt(layerId, x, y)), {
|
|
86
|
+
originX: chunkX * 32,
|
|
87
|
+
originY: chunkY * 32,
|
|
88
|
+
cellSize: map.tileWidth,
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
map.onTileChanged(({ x, y, tile }) => window.setCost(x, y, walkCost(tile)));
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Cost `0` blocks a cell, `1` is ordinary ground, larger values are terrain the search routes
|
|
95
|
+
around when the detour is cheaper. Diagonal steps cost their length, and the default diagonal
|
|
96
|
+
policy (`'no-corner-cutting'`) forbids the diagonal that would clip through the corner where two
|
|
97
|
+
walls meet.
|
|
98
|
+
|
|
99
|
+
`agentSize` restricts a query to cells where an agent that many cells wide fits. Clearance is
|
|
100
|
+
anchored at a cell's **top-left** corner, so the last row and column of a window can never hold
|
|
101
|
+
an agent wider than one cell.
|
|
102
|
+
|
|
103
|
+
## Jump-point search
|
|
104
|
+
|
|
105
|
+
`GridSpace` substitutes jump-point search for plain neighbour expansion whenever the grid is
|
|
106
|
+
uniform-cost, `agentSize` is `1`, and the diagonal policy is the default. It returns the same
|
|
107
|
+
cost-optimal path while expanding a fraction of the nodes; `result.expandedNodes` shows the
|
|
108
|
+
difference. Nothing has to be switched on, and `{ pruning: false }` switches it off.
|
|
109
|
+
|
|
110
|
+
Because pruning settles only jump points, a `budget-exceeded` partial path under pruning ends on
|
|
111
|
+
a jump point rather than on the nearest cell. `snapToNearest` is unaffected: when the goal turns
|
|
112
|
+
out to be unreachable, the query re-runs unpruned so the snapped node really is the closest one.
|
|
113
|
+
|
|
114
|
+
## Waypoint graphs
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
import { Pathfinder, WaypointGraph } from '@codexo/exojs-pathfinding';
|
|
118
|
+
|
|
119
|
+
interface Move {
|
|
120
|
+
readonly impulse: number;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const graph = new WaypointGraph<Move>();
|
|
124
|
+
const ledge = graph.addNode(120, 400);
|
|
125
|
+
const platform = graph.addNode(320, 260);
|
|
126
|
+
|
|
127
|
+
graph.connect(ledge, platform, { kind: 'jump', data: { impulse: 520 }, cost: 40 });
|
|
128
|
+
|
|
129
|
+
for (const step of new Pathfinder().findPath(graph, ledge, platform).edges) {
|
|
130
|
+
controller.execute(step.kind, step.data);
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Node positions are optional. Leave them out and the heuristic drops to zero, which turns the
|
|
135
|
+
same search into plain Dijkstra over an abstract graph - the shape a web application's routing
|
|
136
|
+
problem usually has.
|
|
137
|
+
|
|
138
|
+
## Reachable-area queries
|
|
139
|
+
|
|
140
|
+
`floodFrom` returns every node within a cost budget, cheapest first: the "tiles I can still
|
|
141
|
+
reach with the movement points I have left" query, and the input a flow field would be built
|
|
142
|
+
from.
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
const region = pathfinder.floodFrom(grid, grid.nodeAt(unit.tileX, unit.tileY), { maxCost: 6 });
|
|
146
|
+
|
|
147
|
+
for (const node of region.nodes) {
|
|
148
|
+
highlight(grid.nodeX(node), grid.nodeY(node));
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
## Determinism and allocation
|
|
153
|
+
|
|
154
|
+
Equal-cost paths are resolved by a pinned tie-break (lower node id first), so the same query on
|
|
155
|
+
an unmutated space returns the identical path on every machine and every run - which is what
|
|
156
|
+
makes paths safe to record in a replay or assert in a test.
|
|
157
|
+
|
|
158
|
+
A `Pathfinder` owns its search state and reuses it across queries, including queries against
|
|
159
|
+
different spaces of different sizes. Once the buffers have grown to fit, a search allocates
|
|
160
|
+
nothing that scales with the number of nodes it visits. The result object is allocated fresh
|
|
161
|
+
every time, deliberately: callers keep paths, and pooling something a caller keeps buys a little
|
|
162
|
+
garbage back at the price of use-after-reuse bugs.
|
|
163
|
+
|
|
164
|
+
## Custom spaces
|
|
165
|
+
|
|
166
|
+
Implement `NavigationSpace` and every query in this package works against it. `neighbors`
|
|
167
|
+
receives the pathfinder's own buffers instead of returning an array, so a third-party space is
|
|
168
|
+
allocation-free on the same terms as the built-in ones.
|
|
169
|
+
|
|
170
|
+
## License
|
|
171
|
+
|
|
172
|
+
MIT
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { FindPathOptions, FloodOptions, FloodRegion, NavigationSpace, PathResult } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Runs path queries against any {@link NavigationSpace}.
|
|
4
|
+
*
|
|
5
|
+
* One pathfinder owns the search buffers and reuses them across every query,
|
|
6
|
+
* including queries against different spaces of different sizes, so a search
|
|
7
|
+
* itself allocates nothing once the buffers have reached their size. The result
|
|
8
|
+
* objects are freshly allocated by design: callers hold on to a path, and
|
|
9
|
+
* pooling something a caller retains trades a little garbage for use-after-reuse
|
|
10
|
+
* bugs.
|
|
11
|
+
*
|
|
12
|
+
* A pathfinder holds no world state and no lifecycle - construct one per system
|
|
13
|
+
* that needs paths, or share one, as long as queries do not interleave with a
|
|
14
|
+
* mutation of the space being searched.
|
|
15
|
+
*/
|
|
16
|
+
export declare class Pathfinder {
|
|
17
|
+
private readonly state;
|
|
18
|
+
private readonly reversed;
|
|
19
|
+
/**
|
|
20
|
+
* Finds a cost-optimal path between two node ids.
|
|
21
|
+
*
|
|
22
|
+
* `unreachable` yields an empty path unless {@link FindPathOptions.snapToNearest}
|
|
23
|
+
* is set; `budget-exceeded` always carries the best partial path found, which
|
|
24
|
+
* is a real, traversable prefix and not a guess at the rest.
|
|
25
|
+
*/
|
|
26
|
+
findPath<Payload>(space: NavigationSpace<Payload>, start: number, goal: number, options?: FindPathOptions): PathResult<Payload>;
|
|
27
|
+
/**
|
|
28
|
+
* {@link findPath} between two points instead of node ids. A point outside the
|
|
29
|
+
* space makes the query `unreachable` unless
|
|
30
|
+
* {@link FindPathOptions.snapToNearest} is set and the space can resolve a
|
|
31
|
+
* nearest node.
|
|
32
|
+
*/
|
|
33
|
+
findPathBetween<Payload>(space: NavigationSpace<Payload>, startX: number, startY: number, goalX: number, goalY: number, options?: FindPathOptions): PathResult<Payload>;
|
|
34
|
+
/**
|
|
35
|
+
* Every node reachable from `origin` within {@link FloodOptions.maxCost}, with
|
|
36
|
+
* its cost - the "tiles I can still move to this turn" query, and the input a
|
|
37
|
+
* flow field for many agents heading to one goal is built from.
|
|
38
|
+
*/
|
|
39
|
+
floodFrom(space: NavigationSpace, origin: number, options?: FloodOptions): FloodRegion;
|
|
40
|
+
private resolve;
|
|
41
|
+
/**
|
|
42
|
+
* Walks the parent chain back from `end` and writes it forwards into `out`.
|
|
43
|
+
* With a pruned expansion the chain holds jump points only, so each hop is
|
|
44
|
+
* handed back to the expansion to fill in the run it skipped.
|
|
45
|
+
*/
|
|
46
|
+
private reconstruct;
|
|
47
|
+
private toPoints;
|
|
48
|
+
private toEdges;
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=Pathfinder.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Pathfinder.d.ts","sourceRoot":"","sources":["../../src/Pathfinder.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,WAAW,EAAE,eAAe,EAAY,UAAU,EAAmB,MAAM,SAAS,CAAC;AAMlI;;;;;;;;;;;;;GAaG;AACH,qBAAa,UAAU;IACrB,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAqB;IAC3C,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAgB;IAEzC;;;;;;OAMG;IACI,QAAQ,CAAC,OAAO,EAAE,KAAK,EAAE,eAAe,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,eAAoB,GAAG,UAAU,CAAC,OAAO,CAAC;IA0D1I;;;;;OAKG;IACI,eAAe,CAAC,OAAO,EAC5B,KAAK,EAAE,eAAe,CAAC,OAAO,CAAC,EAC/B,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,OAAO,GAAE,eAAoB,GAC5B,UAAU,CAAC,OAAO,CAAC;IAoBtB;;;;OAIG;IACI,SAAS,CAAC,KAAK,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,YAAiB,GAAG,WAAW;IAWjG,OAAO,CAAC,OAAO;IAQf;;;;OAIG;IACH,OAAO,CAAC,WAAW;IAkBnB,OAAO,CAAC,QAAQ;IAahB,OAAO,CAAC,OAAO;CAahB"}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { runFlood, runSearch } from "./core/search.js";
|
|
2
|
+
import { SearchState } from "./core/SearchState.js";
|
|
3
|
+
import { Vector } from "@codexo/exojs";
|
|
4
|
+
|
|
5
|
+
//#region src/Pathfinder.ts
|
|
6
|
+
const EMPTY_NODES = Object.freeze([]);
|
|
7
|
+
const EMPTY_POINTS = Object.freeze([]);
|
|
8
|
+
const EMPTY_EDGES = Object.freeze([]);
|
|
9
|
+
/**
|
|
10
|
+
* Runs path queries against any {@link NavigationSpace}.
|
|
11
|
+
*
|
|
12
|
+
* One pathfinder owns the search buffers and reuses them across every query,
|
|
13
|
+
* including queries against different spaces of different sizes, so a search
|
|
14
|
+
* itself allocates nothing once the buffers have reached their size. The result
|
|
15
|
+
* objects are freshly allocated by design: callers hold on to a path, and
|
|
16
|
+
* pooling something a caller retains trades a little garbage for use-after-reuse
|
|
17
|
+
* bugs.
|
|
18
|
+
*
|
|
19
|
+
* A pathfinder holds no world state and no lifecycle - construct one per system
|
|
20
|
+
* that needs paths, or share one, as long as queries do not interleave with a
|
|
21
|
+
* mutation of the space being searched.
|
|
22
|
+
*/
|
|
23
|
+
var Pathfinder = class {
|
|
24
|
+
state = new SearchState();
|
|
25
|
+
reversed = [];
|
|
26
|
+
/**
|
|
27
|
+
* Finds a cost-optimal path between two node ids.
|
|
28
|
+
*
|
|
29
|
+
* `unreachable` yields an empty path unless {@link FindPathOptions.snapToNearest}
|
|
30
|
+
* is set; `budget-exceeded` always carries the best partial path found, which
|
|
31
|
+
* is a real, traversable prefix and not a guess at the rest.
|
|
32
|
+
*/
|
|
33
|
+
findPath(space, start, goal, options = {}) {
|
|
34
|
+
const agentSize = options.agentSize ?? 1;
|
|
35
|
+
const budget = options.maxExpandedNodes ?? 0;
|
|
36
|
+
const snapToNearest = options.snapToNearest === true;
|
|
37
|
+
this.state.reserve(space.nodeCapacity, space.maxDegree);
|
|
38
|
+
let expansion = options.pruning === false || space.pruning === void 0 ? null : space.pruning(agentSize);
|
|
39
|
+
let outcome = runSearch(this.state, space, start, goal, agentSize, budget, expansion);
|
|
40
|
+
if (outcome.status === "unreachable" && snapToNearest && expansion !== null) {
|
|
41
|
+
expansion = null;
|
|
42
|
+
outcome = runSearch(this.state, space, start, goal, agentSize, budget, null);
|
|
43
|
+
}
|
|
44
|
+
const snapped = outcome.status === "unreachable" && snapToNearest;
|
|
45
|
+
if (outcome.status === "unreachable" && !snapped) return {
|
|
46
|
+
status: "unreachable",
|
|
47
|
+
nodes: EMPTY_NODES,
|
|
48
|
+
points: EMPTY_POINTS,
|
|
49
|
+
edges: EMPTY_EDGES,
|
|
50
|
+
cost: 0,
|
|
51
|
+
revision: space.revision,
|
|
52
|
+
expandedNodes: outcome.expandedNodes
|
|
53
|
+
};
|
|
54
|
+
const nodes = [];
|
|
55
|
+
this.reconstruct(outcome.endNode, expansion, nodes);
|
|
56
|
+
let path = nodes;
|
|
57
|
+
let smoothed = false;
|
|
58
|
+
if (options.smooth === true && space.smoothPath !== void 0) {
|
|
59
|
+
path = space.smoothPath(nodes, agentSize);
|
|
60
|
+
smoothed = true;
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
status: snapped ? "found" : outcome.status,
|
|
64
|
+
nodes: path,
|
|
65
|
+
points: this.toPoints(space, path),
|
|
66
|
+
edges: smoothed ? EMPTY_EDGES : this.toEdges(space, path),
|
|
67
|
+
cost: outcome.cost,
|
|
68
|
+
revision: space.revision,
|
|
69
|
+
expandedNodes: outcome.expandedNodes
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* {@link findPath} between two points instead of node ids. A point outside the
|
|
74
|
+
* space makes the query `unreachable` unless
|
|
75
|
+
* {@link FindPathOptions.snapToNearest} is set and the space can resolve a
|
|
76
|
+
* nearest node.
|
|
77
|
+
*/
|
|
78
|
+
findPathBetween(space, startX, startY, goalX, goalY, options = {}) {
|
|
79
|
+
const snap = options.snapToNearest === true;
|
|
80
|
+
const start = this.resolve(space, startX, startY, snap);
|
|
81
|
+
const goal = this.resolve(space, goalX, goalY, snap);
|
|
82
|
+
if (start < 0 || goal < 0) return {
|
|
83
|
+
status: "unreachable",
|
|
84
|
+
nodes: EMPTY_NODES,
|
|
85
|
+
points: EMPTY_POINTS,
|
|
86
|
+
edges: EMPTY_EDGES,
|
|
87
|
+
cost: 0,
|
|
88
|
+
revision: space.revision,
|
|
89
|
+
expandedNodes: 0
|
|
90
|
+
};
|
|
91
|
+
return this.findPath(space, start, goal, options);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Every node reachable from `origin` within {@link FloodOptions.maxCost}, with
|
|
95
|
+
* its cost - the "tiles I can still move to this turn" query, and the input a
|
|
96
|
+
* flow field for many agents heading to one goal is built from.
|
|
97
|
+
*/
|
|
98
|
+
floodFrom(space, origin, options = {}) {
|
|
99
|
+
const nodes = [];
|
|
100
|
+
const costs = [];
|
|
101
|
+
this.state.reserve(space.nodeCapacity, space.maxDegree);
|
|
102
|
+
const expandedNodes = runFlood(this.state, space, origin, options.agentSize ?? 1, options.maxCost ?? Infinity, options.maxExpandedNodes ?? 0, nodes, costs);
|
|
103
|
+
return {
|
|
104
|
+
nodes,
|
|
105
|
+
costs,
|
|
106
|
+
revision: space.revision,
|
|
107
|
+
expandedNodes
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
resolve(space, x, y, snap) {
|
|
111
|
+
const node = space.pointToNode(x, y);
|
|
112
|
+
if (node >= 0 || !snap || space.nearestNode === void 0) return node;
|
|
113
|
+
return space.nearestNode(x, y);
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Walks the parent chain back from `end` and writes it forwards into `out`.
|
|
117
|
+
* With a pruned expansion the chain holds jump points only, so each hop is
|
|
118
|
+
* handed back to the expansion to fill in the run it skipped.
|
|
119
|
+
*/
|
|
120
|
+
reconstruct(end, expansion, out) {
|
|
121
|
+
const { reversed } = this;
|
|
122
|
+
const { parent } = this.state;
|
|
123
|
+
reversed.length = 0;
|
|
124
|
+
for (let node = end; node >= 0; node = parent[node]) reversed.push(node);
|
|
125
|
+
out.push(reversed[reversed.length - 1]);
|
|
126
|
+
for (let index = reversed.length - 2; index >= 0; index--) if (expansion === null) out.push(reversed[index]);
|
|
127
|
+
else expansion.expand(reversed[index + 1], reversed[index], out);
|
|
128
|
+
}
|
|
129
|
+
toPoints(space, nodes) {
|
|
130
|
+
const points = [];
|
|
131
|
+
for (let index = 0; index < nodes.length; index++) {
|
|
132
|
+
const point = new Vector();
|
|
133
|
+
space.nodeToPoint(nodes[index], point);
|
|
134
|
+
points.push(point);
|
|
135
|
+
}
|
|
136
|
+
return points;
|
|
137
|
+
}
|
|
138
|
+
toEdges(space, nodes) {
|
|
139
|
+
if (space.describeEdge === void 0) return EMPTY_EDGES;
|
|
140
|
+
const edges = [];
|
|
141
|
+
for (let index = 1; index < nodes.length; index++) {
|
|
142
|
+
const edge = space.describeEdge(nodes[index - 1], nodes[index]);
|
|
143
|
+
if (edge !== null) edges.push(edge);
|
|
144
|
+
}
|
|
145
|
+
return edges;
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
//#endregion
|
|
150
|
+
export { Pathfinder };
|
|
151
|
+
//# sourceMappingURL=Pathfinder.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Pathfinder.js","names":[],"sources":["../../src/Pathfinder.ts"],"sourcesContent":["import { Vector } from '@codexo/exojs';\n\nimport { runFlood, runSearch } from './core/search';\nimport { SearchState } from './core/SearchState';\nimport type { FindPathOptions, FloodOptions, FloodRegion, NavigationSpace, PathEdge, PathResult, PrunedExpansion } from './types';\n\nconst EMPTY_NODES: readonly number[] = Object.freeze([]);\nconst EMPTY_POINTS: readonly Vector[] = Object.freeze([]);\nconst EMPTY_EDGES: ReadonlyArray<PathEdge<never>> = Object.freeze([]);\n\n/**\n * Runs path queries against any {@link NavigationSpace}.\n *\n * One pathfinder owns the search buffers and reuses them across every query,\n * including queries against different spaces of different sizes, so a search\n * itself allocates nothing once the buffers have reached their size. The result\n * objects are freshly allocated by design: callers hold on to a path, and\n * pooling something a caller retains trades a little garbage for use-after-reuse\n * bugs.\n *\n * A pathfinder holds no world state and no lifecycle - construct one per system\n * that needs paths, or share one, as long as queries do not interleave with a\n * mutation of the space being searched.\n */\nexport class Pathfinder {\n private readonly state = new SearchState();\n private readonly reversed: number[] = [];\n\n /**\n * Finds a cost-optimal path between two node ids.\n *\n * `unreachable` yields an empty path unless {@link FindPathOptions.snapToNearest}\n * is set; `budget-exceeded` always carries the best partial path found, which\n * is a real, traversable prefix and not a guess at the rest.\n */\n public findPath<Payload>(space: NavigationSpace<Payload>, start: number, goal: number, options: FindPathOptions = {}): PathResult<Payload> {\n const agentSize = options.agentSize ?? 1;\n const budget = options.maxExpandedNodes ?? 0;\n const snapToNearest = options.snapToNearest === true;\n\n this.state.reserve(space.nodeCapacity, space.maxDegree);\n\n let expansion = options.pruning === false || space.pruning === undefined ? null : space.pruning(agentSize);\n let outcome = runSearch(this.state, space, start, goal, agentSize, budget, expansion);\n\n // A pruned expansion only ever settles jump points, so the closest node it\n // can name is a jump point and not the nearest reachable one. Re-running\n // unpruned costs a second search, but only on the path where the first one\n // already failed to reach the goal.\n if (outcome.status === 'unreachable' && snapToNearest && expansion !== null) {\n expansion = null;\n outcome = runSearch(this.state, space, start, goal, agentSize, budget, null);\n }\n\n const snapped = outcome.status === 'unreachable' && snapToNearest;\n\n if (outcome.status === 'unreachable' && !snapped) {\n return {\n status: 'unreachable',\n nodes: EMPTY_NODES,\n points: EMPTY_POINTS,\n edges: EMPTY_EDGES,\n cost: 0,\n revision: space.revision,\n expandedNodes: outcome.expandedNodes,\n };\n }\n\n const nodes: number[] = [];\n\n this.reconstruct(outcome.endNode, expansion, nodes);\n\n let path = nodes;\n let smoothed = false;\n\n if (options.smooth === true && space.smoothPath !== undefined) {\n path = space.smoothPath(nodes, agentSize);\n smoothed = true;\n }\n\n return {\n status: snapped ? 'found' : outcome.status,\n nodes: path,\n points: this.toPoints(space, path),\n // A smoothed path no longer steps along space edges, so there is nothing\n // truthful to report for it.\n edges: smoothed ? EMPTY_EDGES : this.toEdges(space, path),\n cost: outcome.cost,\n revision: space.revision,\n expandedNodes: outcome.expandedNodes,\n };\n }\n\n /**\n * {@link findPath} between two points instead of node ids. A point outside the\n * space makes the query `unreachable` unless\n * {@link FindPathOptions.snapToNearest} is set and the space can resolve a\n * nearest node.\n */\n public findPathBetween<Payload>(\n space: NavigationSpace<Payload>,\n startX: number,\n startY: number,\n goalX: number,\n goalY: number,\n options: FindPathOptions = {},\n ): PathResult<Payload> {\n const snap = options.snapToNearest === true;\n const start = this.resolve(space, startX, startY, snap);\n const goal = this.resolve(space, goalX, goalY, snap);\n\n if (start < 0 || goal < 0) {\n return {\n status: 'unreachable',\n nodes: EMPTY_NODES,\n points: EMPTY_POINTS,\n edges: EMPTY_EDGES,\n cost: 0,\n revision: space.revision,\n expandedNodes: 0,\n };\n }\n\n return this.findPath(space, start, goal, options);\n }\n\n /**\n * Every node reachable from `origin` within {@link FloodOptions.maxCost}, with\n * its cost - the \"tiles I can still move to this turn\" query, and the input a\n * flow field for many agents heading to one goal is built from.\n */\n public floodFrom(space: NavigationSpace, origin: number, options: FloodOptions = {}): FloodRegion {\n const nodes: number[] = [];\n const costs: number[] = [];\n\n this.state.reserve(space.nodeCapacity, space.maxDegree);\n\n const expandedNodes = runFlood(this.state, space, origin, options.agentSize ?? 1, options.maxCost ?? Infinity, options.maxExpandedNodes ?? 0, nodes, costs);\n\n return { nodes, costs, revision: space.revision, expandedNodes };\n }\n\n private resolve(space: NavigationSpace, x: number, y: number, snap: boolean): number {\n const node = space.pointToNode(x, y);\n\n if (node >= 0 || !snap || space.nearestNode === undefined) return node;\n\n return space.nearestNode(x, y);\n }\n\n /**\n * Walks the parent chain back from `end` and writes it forwards into `out`.\n * With a pruned expansion the chain holds jump points only, so each hop is\n * handed back to the expansion to fill in the run it skipped.\n */\n private reconstruct(end: number, expansion: PrunedExpansion | null, out: number[]): void {\n const { reversed } = this;\n const { parent } = this.state;\n\n reversed.length = 0;\n\n for (let node = end; node >= 0; node = parent[node]!) {\n reversed.push(node);\n }\n\n out.push(reversed[reversed.length - 1]!);\n\n for (let index = reversed.length - 2; index >= 0; index--) {\n if (expansion === null) out.push(reversed[index]!);\n else expansion.expand(reversed[index + 1]!, reversed[index]!, out);\n }\n }\n\n private toPoints(space: NavigationSpace, nodes: readonly number[]): Vector[] {\n const points: Vector[] = [];\n\n for (let index = 0; index < nodes.length; index++) {\n const point = new Vector();\n\n space.nodeToPoint(nodes[index]!, point);\n points.push(point);\n }\n\n return points;\n }\n\n private toEdges<Payload>(space: NavigationSpace<Payload>, nodes: readonly number[]): ReadonlyArray<PathEdge<Payload>> {\n if (space.describeEdge === undefined) return EMPTY_EDGES;\n\n const edges: Array<PathEdge<Payload>> = [];\n\n for (let index = 1; index < nodes.length; index++) {\n const edge = space.describeEdge(nodes[index - 1]!, nodes[index]!);\n\n if (edge !== null) edges.push(edge);\n }\n\n return edges;\n }\n}\n"],"mappings":";;;;;AAMA,MAAM,cAAiC,OAAO,OAAO,CAAC,CAAC;AACvD,MAAM,eAAkC,OAAO,OAAO,CAAC,CAAC;AACxD,MAAM,cAA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IAAI,QAAQ,SAAS,SAAS,GAAG,SAAS,GAAG,SAChD,IAAI,cAAc,MAAM,IAAI,KAAK,SAAS,MAAO;OAC5C,UAAU,OAAO,SAAS,QAAQ,IAAK,SAAS,QAAS,GAAG;CAErE;CAEA,AAAQ,SAAS,OAAwB,OAAoC;EAC3E,MAAM,SAAmB,CAAC;EAE1B,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS;GACjD,MAAM,QAAQ,IAAI,OAAO;GAEzB,MAAM,YAAY,MAAM,QAAS,KAAK;GACtC,OAAO,KAAK,KAAK;EACnB;EAEA,OAAO;CACT;CAEA,AAAQ,QAAiB,OAAiC,OAA4D;EACpH,IAAI,MAAM,iBAAiB,QAAW,OAAO;EAE7C,MAAM,QAAkC,CAAC;EAEzC,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS;GACjD,MAAM,OAAO,MAAM,aAAa,MAAM,QAAQ,IAAK,MAAM,MAAO;GAEhE,IAAI,SAAS,MAAM,MAAM,KAAK,IAAI;EACpC;EAEA,OAAO;CACT;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BinaryHeap.d.ts","sourceRoot":"","sources":["../../../src/core/BinaryHeap.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
//#region src/core/BinaryHeap.ts
|
|
2
|
+
/**
|
|
3
|
+
* Min-heap of `(key, node)` pairs over two parallel typed arrays.
|
|
4
|
+
*
|
|
5
|
+
* Ties on `key` are broken by the lower node id, which is what makes a search
|
|
6
|
+
* reproducible: equal-f nodes come off the open list in the same order on every
|
|
7
|
+
* platform and every run, so two identical queries return the identical path
|
|
8
|
+
* rather than an arbitrary member of the optimal set.
|
|
9
|
+
*
|
|
10
|
+
* The heap grows by doubling and never shrinks, so a pathfinder that has run
|
|
11
|
+
* once at a given problem size does not allocate here again.
|
|
12
|
+
*
|
|
13
|
+
* @internal
|
|
14
|
+
*/
|
|
15
|
+
var BinaryHeap = class {
|
|
16
|
+
nodes;
|
|
17
|
+
keys;
|
|
18
|
+
count = 0;
|
|
19
|
+
constructor(capacity = 64) {
|
|
20
|
+
this.nodes = new Int32Array(capacity);
|
|
21
|
+
this.keys = new Float64Array(capacity);
|
|
22
|
+
}
|
|
23
|
+
get size() {
|
|
24
|
+
return this.count;
|
|
25
|
+
}
|
|
26
|
+
clear() {
|
|
27
|
+
this.count = 0;
|
|
28
|
+
}
|
|
29
|
+
push(node, key) {
|
|
30
|
+
if (this.count === this.nodes.length) this.grow();
|
|
31
|
+
let index = this.count++;
|
|
32
|
+
this.nodes[index] = node;
|
|
33
|
+
this.keys[index] = key;
|
|
34
|
+
while (index > 0) {
|
|
35
|
+
const parent = index - 1 >> 1;
|
|
36
|
+
if (!this.less(index, parent)) break;
|
|
37
|
+
this.swap(index, parent);
|
|
38
|
+
index = parent;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** Removes and returns the minimum node. The heap must not be empty. */
|
|
42
|
+
pop() {
|
|
43
|
+
const top = this.nodes[0];
|
|
44
|
+
const last = --this.count;
|
|
45
|
+
if (last > 0) {
|
|
46
|
+
this.nodes[0] = this.nodes[last];
|
|
47
|
+
this.keys[0] = this.keys[last];
|
|
48
|
+
this.sink();
|
|
49
|
+
}
|
|
50
|
+
return top;
|
|
51
|
+
}
|
|
52
|
+
less(a, b) {
|
|
53
|
+
const keyA = this.keys[a];
|
|
54
|
+
const keyB = this.keys[b];
|
|
55
|
+
if (keyA !== keyB) return keyA < keyB;
|
|
56
|
+
return this.nodes[a] < this.nodes[b];
|
|
57
|
+
}
|
|
58
|
+
swap(a, b) {
|
|
59
|
+
const node = this.nodes[a];
|
|
60
|
+
const key = this.keys[a];
|
|
61
|
+
this.nodes[a] = this.nodes[b];
|
|
62
|
+
this.keys[a] = this.keys[b];
|
|
63
|
+
this.nodes[b] = node;
|
|
64
|
+
this.keys[b] = key;
|
|
65
|
+
}
|
|
66
|
+
sink() {
|
|
67
|
+
let index = 0;
|
|
68
|
+
for (;;) {
|
|
69
|
+
const left = index * 2 + 1;
|
|
70
|
+
if (left >= this.count) break;
|
|
71
|
+
const right = left + 1;
|
|
72
|
+
const child = right < this.count && this.less(right, left) ? right : left;
|
|
73
|
+
if (!this.less(child, index)) break;
|
|
74
|
+
this.swap(index, child);
|
|
75
|
+
index = child;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
grow() {
|
|
79
|
+
const nodes = new Int32Array(this.nodes.length * 2);
|
|
80
|
+
const keys = new Float64Array(this.keys.length * 2);
|
|
81
|
+
nodes.set(this.nodes);
|
|
82
|
+
keys.set(this.keys);
|
|
83
|
+
this.nodes = nodes;
|
|
84
|
+
this.keys = keys;
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
//#endregion
|
|
89
|
+
export { BinaryHeap };
|
|
90
|
+
//# sourceMappingURL=BinaryHeap.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BinaryHeap.js","names":[],"sources":["../../../src/core/BinaryHeap.ts"],"sourcesContent":["/**\n * Min-heap of `(key, node)` pairs over two parallel typed arrays.\n *\n * Ties on `key` are broken by the lower node id, which is what makes a search\n * reproducible: equal-f nodes come off the open list in the same order on every\n * platform and every run, so two identical queries return the identical path\n * rather than an arbitrary member of the optimal set.\n *\n * The heap grows by doubling and never shrinks, so a pathfinder that has run\n * once at a given problem size does not allocate here again.\n *\n * @internal\n */\nexport class BinaryHeap {\n private nodes: Int32Array;\n private keys: Float64Array;\n private count = 0;\n\n public constructor(capacity = 64) {\n this.nodes = new Int32Array(capacity);\n this.keys = new Float64Array(capacity);\n }\n\n public get size(): number {\n return this.count;\n }\n\n public clear(): void {\n this.count = 0;\n }\n\n public push(node: number, key: number): void {\n if (this.count === this.nodes.length) this.grow();\n\n let index = this.count++;\n\n this.nodes[index] = node;\n this.keys[index] = key;\n\n while (index > 0) {\n const parent = (index - 1) >> 1;\n\n if (!this.less(index, parent)) break;\n\n this.swap(index, parent);\n index = parent;\n }\n }\n\n /** Removes and returns the minimum node. The heap must not be empty. */\n public pop(): number {\n const top = this.nodes[0]!;\n const last = --this.count;\n\n if (last > 0) {\n this.nodes[0] = this.nodes[last]!;\n this.keys[0] = this.keys[last]!;\n this.sink();\n }\n\n return top;\n }\n\n private less(a: number, b: number): boolean {\n const keyA = this.keys[a]!;\n const keyB = this.keys[b]!;\n\n if (keyA !== keyB) return keyA < keyB;\n\n return this.nodes[a]! < this.nodes[b]!;\n }\n\n private swap(a: number, b: number): void {\n const node = this.nodes[a]!;\n const key = this.keys[a]!;\n\n this.nodes[a] = this.nodes[b]!;\n this.keys[a] = this.keys[b]!;\n this.nodes[b] = node;\n this.keys[b] = key;\n }\n\n private sink(): void {\n let index = 0;\n\n for (;;) {\n const left = index * 2 + 1;\n\n if (left >= this.count) break;\n\n const right = left + 1;\n const child = right < this.count && this.less(right, left) ? right : left;\n\n if (!this.less(child, index)) break;\n\n this.swap(index, child);\n index = child;\n }\n }\n\n private grow(): void {\n const nodes = new Int32Array(this.nodes.length * 2);\n const keys = new Float64Array(this.keys.length * 2);\n\n nodes.set(this.nodes);\n keys.set(this.keys);\n\n this.nodes = nodes;\n this.keys = keys;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAaA,IAAa,aAAb,MAAwB;CACtB,AAAQ;CACR,AAAQ;CACR,AAAQ,QAAQ;CAEhB,AAAO,YAAY,WAAW,IAAI;EAChC,KAAK,QAAQ,IAAI,WAAW,QAAQ;EACpC,KAAK,OAAO,IAAI,aAAa,QAAQ;CACvC;CAEA,IAAW,OAAe;EACxB,OAAO,KAAK;CACd;CAEA,AAAO,QAAc;EACnB,KAAK,QAAQ;CACf;CAEA,AAAO,KAAK,MAAc,KAAmB;EAC3C,IAAI,KAAK,UAAU,KAAK,MAAM,QAAQ,KAAK,KAAK;EAEhD,IAAI,QAAQ,KAAK;EAEjB,KAAK,MAAM,SAAS;EACpB,KAAK,KAAK,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C;EAElD,MAAM,IAAI,KAAK,KAAK;EACpB,KAAK,IAAI,KAAK,IAAI;EAElB,KAAK,QAAQ;EACb,KAAK,OAAO;CACd;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SearchState.d.ts","sourceRoot":"","sources":["../../../src/core/SearchState.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { BinaryHeap } from "./BinaryHeap.js";
|
|
2
|
+
|
|
3
|
+
//#region src/core/SearchState.ts
|
|
4
|
+
/** Largest generation stamp before the counter has to wrap. */
|
|
5
|
+
const MAX_GENERATION = 4294967295;
|
|
6
|
+
/**
|
|
7
|
+
* Reusable per-search bookkeeping: g-scores, parent links, the closed set, the
|
|
8
|
+
* open list and the neighbour scratch buffers.
|
|
9
|
+
*
|
|
10
|
+
* Nothing is cleared between searches. A node's g-score, parent and closed flag
|
|
11
|
+
* count only while its generation stamp matches the current one, so starting a
|
|
12
|
+
* search is a single counter increment instead of an O(nodeCapacity) wipe. That
|
|
13
|
+
* is what lets one pathfinder serve interleaved queries over several spaces of
|
|
14
|
+
* different sizes without touching memory it does not visit.
|
|
15
|
+
*
|
|
16
|
+
* @internal
|
|
17
|
+
*/
|
|
18
|
+
var SearchState = class {
|
|
19
|
+
gScore = /* @__PURE__ */ new Float64Array(0);
|
|
20
|
+
parent = /* @__PURE__ */ new Int32Array(0);
|
|
21
|
+
closed = /* @__PURE__ */ new Uint8Array(0);
|
|
22
|
+
neighborNodes = /* @__PURE__ */ new Int32Array(0);
|
|
23
|
+
neighborCosts = /* @__PURE__ */ new Float64Array(0);
|
|
24
|
+
heap = new BinaryHeap();
|
|
25
|
+
stamp = /* @__PURE__ */ new Uint32Array(0);
|
|
26
|
+
generation = 0;
|
|
27
|
+
/** Grows the buffers to fit a space, keeping the generation stamps valid. */
|
|
28
|
+
reserve(nodeCapacity, degree) {
|
|
29
|
+
if (nodeCapacity > this.gScore.length) {
|
|
30
|
+
const stamp = new Uint32Array(nodeCapacity);
|
|
31
|
+
stamp.set(this.stamp);
|
|
32
|
+
this.gScore = new Float64Array(nodeCapacity);
|
|
33
|
+
this.parent = new Int32Array(nodeCapacity);
|
|
34
|
+
this.closed = new Uint8Array(nodeCapacity);
|
|
35
|
+
this.stamp = stamp;
|
|
36
|
+
}
|
|
37
|
+
if (degree > this.neighborNodes.length) {
|
|
38
|
+
this.neighborNodes = new Int32Array(degree);
|
|
39
|
+
this.neighborCosts = new Float64Array(degree);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
begin() {
|
|
43
|
+
if (this.generation === MAX_GENERATION) {
|
|
44
|
+
this.stamp.fill(0);
|
|
45
|
+
this.generation = 0;
|
|
46
|
+
}
|
|
47
|
+
this.generation++;
|
|
48
|
+
this.heap.clear();
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Brings a node into the current search, resetting it on first touch.
|
|
52
|
+
* Returns `true` when the node was already part of this search.
|
|
53
|
+
*/
|
|
54
|
+
touch(node) {
|
|
55
|
+
if (this.stamp[node] === this.generation) return true;
|
|
56
|
+
this.stamp[node] = this.generation;
|
|
57
|
+
this.gScore[node] = Infinity;
|
|
58
|
+
this.parent[node] = -1;
|
|
59
|
+
this.closed[node] = 0;
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
//#endregion
|
|
65
|
+
export { SearchState };
|
|
66
|
+
//# sourceMappingURL=SearchState.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SearchState.js","names":[],"sources":["../../../src/core/SearchState.ts"],"sourcesContent":["import { BinaryHeap } from './BinaryHeap';\n\n/** Largest generation stamp before the counter has to wrap. */\nconst MAX_GENERATION = 0xffffffff;\n\n/**\n * Reusable per-search bookkeeping: g-scores, parent links, the closed set, the\n * open list and the neighbour scratch buffers.\n *\n * Nothing is cleared between searches. A node's g-score, parent and closed flag\n * count only while its generation stamp matches the current one, so starting a\n * search is a single counter increment instead of an O(nodeCapacity) wipe. That\n * is what lets one pathfinder serve interleaved queries over several spaces of\n * different sizes without touching memory it does not visit.\n *\n * @internal\n */\nexport class SearchState {\n public gScore = new Float64Array(0);\n public parent = new Int32Array(0);\n public closed = new Uint8Array(0);\n public neighborNodes = new Int32Array(0);\n public neighborCosts = new Float64Array(0);\n public readonly heap = new BinaryHeap();\n\n private stamp = new Uint32Array(0);\n private generation = 0;\n\n /** Grows the buffers to fit a space, keeping the generation stamps valid. */\n public reserve(nodeCapacity: number, degree: number): void {\n if (nodeCapacity > this.gScore.length) {\n const stamp = new Uint32Array(nodeCapacity);\n\n stamp.set(this.stamp);\n\n this.gScore = new Float64Array(nodeCapacity);\n this.parent = new Int32Array(nodeCapacity);\n this.closed = new Uint8Array(nodeCapacity);\n this.stamp = stamp;\n }\n\n if (degree > this.neighborNodes.length) {\n this.neighborNodes = new Int32Array(degree);\n this.neighborCosts = new Float64Array(degree);\n }\n }\n\n public begin(): void {\n if (this.generation === MAX_GENERATION) {\n this.stamp.fill(0);\n this.generation = 0;\n }\n\n this.generation++;\n this.heap.clear();\n }\n\n /**\n * Brings a node into the current search, resetting it on first touch.\n * Returns `true` when the node was already part of this search.\n */\n public touch(node: number): boolean {\n if (this.stamp[node] === this.generation) return true;\n\n this.stamp[node] = this.generation;\n this.gScore[node] = Infinity;\n this.parent[node] = -1;\n this.closed[node] = 0;\n\n return false;\n }\n}\n"],"mappings":";;;;AAGA,MAAM,iBAAiB;;;;;;;;;;;;;AAcvB,IAAa,cAAb,MAAyB;CACvB,AAAO,yBAAS,IAAI,aAAa,CAAC;CAClC,AAAO,yBAAS,IAAI,WAAW,CAAC;CAChC,AAAO,yBAAS,IAAI,WAAW,CAAC;CAChC,AAAO,gCAAgB,IAAI,WAAW,CAAC;CACvC,AAAO,gCAAgB,IAAI,aAAa,CAAC;CACzC,AAAgB,OAAO,IAAI,WAAW;CAEtC,AAAQ,wBAAQ,IAAI,YAAY,CAAC;CACjC,AAAQ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