@pocketrts/grid 0.4.0 → 0.5.0

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @pocketrts/grid
2
2
 
3
- Grid algorithms for real-time strategy games on an 8-connected cell grid: flow fields shared by whole armies and computed under a fixed per-step budget, bounded local A*, straight-line reach, nearest free cell, distance fields, bucket grids for neighbour queries, field of view, polygons, 8-connected wall chains, line formations and a complete elastic-column march system. Pure logic over typed arrays, deterministic (only `@pocketrts/determinism` math), no DOM. Extracted from Pocket War, where it moves thousands of units.
3
+ Grid algorithms for real-time strategy games on an 8-connected cell grid: flow fields shared by whole armies and computed under a fixed per-step budget, bounded local A*, float-cost A* within an area, 4-connected regions, straight-line reach, nearest free cell, distance fields, bucket grids for neighbour queries, field of view, polygons, 8-connected wall chains, line formations and a complete elastic-column march system. Pure logic over typed arrays, deterministic (only `@pocketrts/determinism` math), no DOM.
4
4
 
5
5
  Try it: [`apps/grid-demo`](../../apps/grid-demo) (`pnpm --filter @pocketrts/grid-demo dev`).
6
6
 
@@ -26,6 +26,8 @@ ES module, TypeScript types included. Depends on `@pocketrts/determinism`.
26
26
  | `FlowFields`, `FlowField`, `FlowLayer`, `FlowFieldOptions`, `DEFAULT_FLOW_FIELD_OPTIONS` | Flow-field cache over one or more layers (`cost` in tenths, 0 = impassable, outer ring must be 0; `canStep`, `canStepDiag`). `get(key, layer, tick, seeds)` returns the cached field or starts one; `maintain(tick)` once per step advances searches within `budget` heap pops, recomputes fields still in use after `invalidate()` and swaps them in whole, and evicts unused ones; `finish(field)` completes one at once. A field's `dirs[cell]` is a direction, `DIR_HERE` on a goal, `DIR_NONE` where not reached yet. |
27
27
  | `cornerFree(block, w, a, b)` | The usual diagonal rule. |
28
28
  | `LocalPathfinder`, `LocalStepRules` | Reusable bounded A* (`find(w, h, start, goal, limit, rules)`, path in `path` / `length`, goal first); gives up beyond `limit` cells of path or `maxNodes` expansions. For short detours where a flow field per target would be waste. |
29
+ | `CostPathfinder`, `CellArea` | Reusable A* over per-cell float costs (0 = impassable) inside a rectangle of cells, with no length limit, for laying roads or rails on a generated map. `find(w, h, start, goal, area, cost, pull)` searches within `area`; `findAround(w, h, start, goal, margin, bounds, cost, pull)` first within the box around both ends widened by `margin`, then on failure within all of `bounds`. Path in `path` / `length`, goal first. |
30
+ | `gridRegions(w, h, passable)`, `GridRegions` | Label the 4-connected regions of passable cells: `region` per cell (-1 impassable, numbered in row-major order of each region's first cell), `sizes`, and `largest` (most cells, lowest number on a tie, -1 if none). |
29
31
  | `lineReach(ax, ay, bx, by, cellSize, w, stuck, sample?)` | Fraction of a straight move that is clear, sampled along the line, with the corner rule. |
30
32
  | `nearestCell(w, h, cell, maxR, ok)` | Closest cell (Euclidean, ring by ring) that `ok` accepts. |
31
33
  | `chamferDistance(src, w, h)` | Two-pass distance to the nearest source cell. |
@@ -137,9 +139,10 @@ Several sides with different passability (gates that open only for their owner,
137
139
 
138
140
  ## Notes
139
141
 
142
+ - Results are bit-identical on every peer and engine within one version, but may change between versions: an improvement becomes the default with no way back to earlier results. Every peer of a match must run the same version, and a recording replays only with the version that produced it.
140
143
  - Flow-field costs are integers in tenths; distances are summed as integers, so results do not depend on float rounding.
141
144
  - `FlowFields.maintain` refreshes one outdated field at a time, every `refreshEvery` steps, while at most one search is queued; until then units keep using the old directions.
142
- - `LocalPathfinder`, `BucketGrid` and the flow-field search reuse their buffers: create one per world, or share one when calls never interleave.
145
+ - `LocalPathfinder`, `CostPathfinder`, `BucketGrid` and the flow-field search reuse their buffers: create one per world, or share one when calls never interleave.
143
146
  - The march system knows nothing of sides, buildings, combat or weather. Whether a group is compact enough to march together, the members' own spots at the goal, unit collisions and what members do when they find their own way are the game's.
144
147
  - Speeds are world units per second, including the `speed` of the units given to `lineFormation`. The defaults suit cells of about 32 units: for other cells use `marchRules(cellSize / 32)` and scale `lineFormation`'s `gap` and `minWidth` alike.
145
148
  - `createMarch` creates the `March` object with its properties in a fixed order, because games hash their state in property order; a game that hashes a march keeps that order.
@@ -0,0 +1,37 @@
1
+ /** A rectangle of cells, corners included. */
2
+ export interface CellArea {
3
+ readonly x0: number;
4
+ readonly y0: number;
5
+ readonly x1: number;
6
+ readonly y1: number;
7
+ }
8
+ export declare class CostPathfinder {
9
+ /** The last path found, goal first, start last (`length` cells). Valid until the next search. */
10
+ path: Int32Array<ArrayBuffer>;
11
+ /** Cells in `path`; 0 after a failed search. */
12
+ length: number;
13
+ private cells;
14
+ private gen;
15
+ private stamp;
16
+ private closed;
17
+ private gScore;
18
+ private parent;
19
+ private heapF;
20
+ private heapC;
21
+ /**
22
+ * Find a path from cell `start` to cell `goal` on a `w` × `h` grid, stepping only onto cells inside `area` (clamped
23
+ * to the grid). Entering a cell costs `cost[cell]`, times √2 on a diagonal step; a cost of 0 means the cell cannot be
24
+ * entered, and a diagonal step is refused when either orthogonal cell beside it costs 0. The estimate is the
25
+ * Euclidean distance to the goal times `pull`; the path is the cheapest when `pull` is at most the cheapest cost in
26
+ * `area`. Returns whether the goal was reached; the path is then in `path` / `length`. The start cell's own cost is
27
+ * not checked.
28
+ */
29
+ find(w: number, h: number, start: number, goal: number, area: CellArea, cost: ArrayLike<number>, pull: number): boolean;
30
+ /**
31
+ * `find` within the bounding box of `start` and `goal` widened by `margin` cells on every side and clamped to
32
+ * `bounds`, which keeps long maps cheap; when that fails, `find` again within all of `bounds`.
33
+ */
34
+ findAround(w: number, h: number, start: number, goal: number, margin: number, bounds: CellArea, cost: ArrayLike<number>, pull: number): boolean;
35
+ private siftUp;
36
+ private growHeap;
37
+ }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * A* over per-cell float costs on an 8-connected grid, inside a rectangular search area: for laying out roads, rails or
3
+ * rivers on a generated map, where terrain makes some cells dearer than others and the route should follow the cheap
4
+ * ones. It has no length limit, and its estimate is scaled by `pull`: at or below the cheapest cost the path is
5
+ * optimal, above it the search runs faster and prefers heading straight for the goal over detours.
6
+ *
7
+ * One instance owns its search buffers and reuses them across calls; it is not re-entrant. Ties are broken by heap
8
+ * order, so the same inputs always give the same path.
9
+ */
10
+ import { dmath } from '@pocketrts/determinism';
11
+ import { DIRX, DIRY } from './dirs.js';
12
+ const SQRT2 = Math.SQRT2;
13
+ export class CostPathfinder {
14
+ /** The last path found, goal first, start last (`length` cells). Valid until the next search. */
15
+ path = new Int32Array(0);
16
+ /** Cells in `path`; 0 after a failed search. */
17
+ length = 0;
18
+ cells = 0;
19
+ gen = 0;
20
+ stamp = new Int32Array(0);
21
+ closed = new Int32Array(0);
22
+ gScore = new Float64Array(0);
23
+ parent = new Int32Array(0);
24
+ heapF = new Float64Array(64);
25
+ heapC = new Int32Array(64);
26
+ /**
27
+ * Find a path from cell `start` to cell `goal` on a `w` × `h` grid, stepping only onto cells inside `area` (clamped
28
+ * to the grid). Entering a cell costs `cost[cell]`, times √2 on a diagonal step; a cost of 0 means the cell cannot be
29
+ * entered, and a diagonal step is refused when either orthogonal cell beside it costs 0. The estimate is the
30
+ * Euclidean distance to the goal times `pull`; the path is the cheapest when `pull` is at most the cheapest cost in
31
+ * `area`. Returns whether the goal was reached; the path is then in `path` / `length`. The start cell's own cost is
32
+ * not checked.
33
+ */
34
+ find(w, h, start, goal, area, cost, pull) {
35
+ const n = w * h;
36
+ if (n !== this.cells) {
37
+ this.cells = n;
38
+ this.stamp = new Int32Array(n);
39
+ this.closed = new Int32Array(n);
40
+ this.gScore = new Float64Array(n);
41
+ this.parent = new Int32Array(n);
42
+ this.gen = 0;
43
+ }
44
+ if (++this.gen === 0x7fffffff) {
45
+ this.stamp.fill(0);
46
+ this.closed.fill(0);
47
+ this.gen = 1;
48
+ }
49
+ this.length = 0;
50
+ const { stamp, closed, gScore, parent, gen } = this;
51
+ const lx = Math.max(0, area.x0), ly = Math.max(0, area.y0);
52
+ const hx = Math.min(w - 1, area.x1), hy = Math.min(h - 1, area.y1);
53
+ const gx = goal % w, gy = (goal / w) | 0;
54
+ let hs = 0, found = false;
55
+ stamp[start] = gen;
56
+ gScore[start] = 0;
57
+ parent[start] = -1;
58
+ this.heapF[0] = 0;
59
+ this.heapC[hs++] = start;
60
+ while (hs > 0) {
61
+ // Re-read on every pop: growHeap replaces the arrays
62
+ const { heapF, heapC } = this;
63
+ const c = heapC[0];
64
+ hs--;
65
+ if (hs > 0) {
66
+ const lf = heapF[hs], lc = heapC[hs];
67
+ let k = 0;
68
+ for (;;) {
69
+ let l = 2 * k + 1;
70
+ if (l >= hs)
71
+ break;
72
+ if (l + 1 < hs && heapF[l + 1] < heapF[l])
73
+ l++;
74
+ if (heapF[l] >= lf)
75
+ break;
76
+ heapF[k] = heapF[l];
77
+ heapC[k] = heapC[l];
78
+ k = l;
79
+ }
80
+ heapF[k] = lf;
81
+ heapC[k] = lc;
82
+ }
83
+ if (closed[c] === gen)
84
+ continue;
85
+ closed[c] = gen;
86
+ if (c === goal) {
87
+ found = true;
88
+ break;
89
+ }
90
+ const cx = c % w, cy = (c / w) | 0, gc = gScore[c];
91
+ for (let d = 0; d < 8; d++) {
92
+ const nx = cx + DIRX[d], ny = cy + DIRY[d];
93
+ if (nx < lx || ny < ly || nx > hx || ny > hy)
94
+ continue;
95
+ const nc = ny * w + nx;
96
+ if (closed[nc] === gen)
97
+ continue;
98
+ const rc = cost[nc];
99
+ if (rc === 0)
100
+ continue;
101
+ if ((d & 1) && (cost[cy * w + nx] === 0 || cost[ny * w + cx] === 0))
102
+ continue;
103
+ const ng = gc + (d & 1 ? rc * SQRT2 : rc);
104
+ if (stamp[nc] === gen && gScore[nc] <= ng)
105
+ continue;
106
+ stamp[nc] = gen;
107
+ gScore[nc] = ng;
108
+ parent[nc] = c;
109
+ if (hs === this.heapF.length)
110
+ this.growHeap();
111
+ this.siftUp(hs++, ng + dmath.hypot(nx - gx, ny - gy) * pull, nc);
112
+ }
113
+ }
114
+ if (!found)
115
+ return false;
116
+ let len = 0;
117
+ for (let c = goal; c !== -1; c = parent[c])
118
+ len++;
119
+ if (this.path.length < len)
120
+ this.path = new Int32Array(len);
121
+ len = 0;
122
+ for (let c = goal; c !== -1; c = parent[c])
123
+ this.path[len++] = c;
124
+ this.length = len;
125
+ return true;
126
+ }
127
+ /**
128
+ * `find` within the bounding box of `start` and `goal` widened by `margin` cells on every side and clamped to
129
+ * `bounds`, which keeps long maps cheap; when that fails, `find` again within all of `bounds`.
130
+ */
131
+ findAround(w, h, start, goal, margin, bounds, cost, pull) {
132
+ const ax = start % w, ay = (start / w) | 0, bx = goal % w, by = (goal / w) | 0;
133
+ const all = {
134
+ x0: Math.max(0, bounds.x0), y0: Math.max(0, bounds.y0), x1: Math.min(w - 1, bounds.x1), y1: Math.min(h - 1, bounds.y1),
135
+ };
136
+ const near = {
137
+ x0: Math.max(all.x0, Math.min(ax, bx) - margin), y0: Math.max(all.y0, Math.min(ay, by) - margin),
138
+ x1: Math.min(all.x1, Math.max(ax, bx) + margin), y1: Math.min(all.y1, Math.max(ay, by) + margin),
139
+ };
140
+ if (this.find(w, h, start, goal, near, cost, pull))
141
+ return true;
142
+ const whole = near.x0 === all.x0 && near.y0 === all.y0 && near.x1 === all.x1 && near.y1 === all.y1;
143
+ return !whole && this.find(w, h, start, goal, all, cost, pull);
144
+ }
145
+ siftUp(k, f, c) {
146
+ const { heapF, heapC } = this;
147
+ while (k > 0) {
148
+ const p = (k - 1) >> 1;
149
+ if (heapF[p] <= f)
150
+ break;
151
+ heapF[k] = heapF[p];
152
+ heapC[k] = heapC[p];
153
+ k = p;
154
+ }
155
+ heapF[k] = f;
156
+ heapC[k] = c;
157
+ }
158
+ growHeap() {
159
+ const f = new Float64Array(this.heapF.length * 2), c = new Int32Array(this.heapC.length * 2);
160
+ f.set(this.heapF);
161
+ c.set(this.heapC);
162
+ this.heapF = f;
163
+ this.heapC = c;
164
+ }
165
+ }
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  export * from './dirs.js';
2
2
  export * from './flowfield.js';
3
3
  export * from './localpath.js';
4
+ export * from './costpath.js';
5
+ export * from './regions.js';
4
6
  export * from './cells.js';
5
7
  export * from './buckets.js';
6
8
  export * from './vision.js';
package/dist/index.js CHANGED
@@ -1,6 +1,8 @@
1
1
  export * from './dirs.js';
2
2
  export * from './flowfield.js';
3
3
  export * from './localpath.js';
4
+ export * from './costpath.js';
5
+ export * from './regions.js';
4
6
  export * from './cells.js';
5
7
  export * from './buckets.js';
6
8
  export * from './vision.js';
package/dist/march.js CHANGED
@@ -418,7 +418,6 @@ function paceTop(g, M) {
418
418
  rowsAt(g, M, g.lead - M.scale, TB, TL, TE, TW);
419
419
  let fold = 1, foldRun = Infinity;
420
420
  for (let r = 0; r < g.rows; r++) {
421
- // Kept in this order, not as (rowE − TE) / scale: with scale 1 the grouping decides the last bit of the result
422
421
  g.rowK[r] = 1 + g.rowE[r] / M.scale - TE[r] / M.scale;
423
422
  const fr = g.rowLen[r] / g.rowD[r];
424
423
  if (fr > 1 && g.rowRun[r] < foldRun)
@@ -0,0 +1,11 @@
1
+ /** The result of `gridRegions`. */
2
+ export interface GridRegions {
3
+ /** Per cell, its region number (0, 1, … in row-major order of each region's first cell), or -1 when impassable. */
4
+ readonly region: Int32Array;
5
+ /** Cells in each region, indexed by region number. */
6
+ readonly sizes: number[];
7
+ /** The region with the most cells, the lowest-numbered one on a tie; -1 when no cell is passable. */
8
+ readonly largest: number;
9
+ }
10
+ /** Label the 4-connected regions of the cells of a `w` × `h` grid that `passable` accepts. */
11
+ export declare function gridRegions(w: number, h: number, passable: (cell: number) => boolean): GridRegions;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * 4-connected regions of passable cells: which cells can reach each other moving only straight, and which region is
3
+ * the largest (the main landmass of a generated map, say). What counts as passable is the caller's.
4
+ */
5
+ import { DIRX, DIRY } from './dirs.js';
6
+ /** Label the 4-connected regions of the cells of a `w` × `h` grid that `passable` accepts. */
7
+ export function gridRegions(w, h, passable) {
8
+ const n = w * h;
9
+ const region = new Int32Array(n).fill(-1);
10
+ const queue = new Int32Array(n);
11
+ const sizes = [];
12
+ let largest = -1, largestSize = 0;
13
+ for (let s = 0; s < n; s++) {
14
+ if (region[s] >= 0 || !passable(s))
15
+ continue;
16
+ const label = sizes.length;
17
+ let head = 0, tail = 0;
18
+ queue[tail++] = s;
19
+ region[s] = label;
20
+ while (head < tail) {
21
+ const c = queue[head++], x = c % w, y = (c / w) | 0;
22
+ for (let d = 0; d < 8; d += 2) {
23
+ const nx = x + DIRX[d], ny = y + DIRY[d];
24
+ if (nx < 0 || ny < 0 || nx >= w || ny >= h)
25
+ continue;
26
+ const j = ny * w + nx;
27
+ if (region[j] < 0 && passable(j)) {
28
+ region[j] = label;
29
+ queue[tail++] = j;
30
+ }
31
+ }
32
+ }
33
+ sizes.push(tail);
34
+ if (tail > largestSize) {
35
+ largestSize = tail;
36
+ largest = label;
37
+ }
38
+ }
39
+ return { region, sizes, largest };
40
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@pocketrts/grid",
3
- "version": "0.4.0",
4
- "description": "Grid algorithms for RTS games: budgeted flow fields, bounded local A*, line reach, distance fields, bucket grids, field of view, polygons, cell chains, line formations and column march",
3
+ "version": "0.5.0",
4
+ "description": "Grid algorithms for RTS games: budgeted flow fields, bounded local A*, float-cost A* within an area, 4-connected regions, line reach, distance fields, bucket grids, field of view, polygons, cell chains, line formations and column march",
5
5
  "license": "MIT",
6
6
  "author": "Junjie Bai <bjj19851010@gmail.com>",
7
7
  "repository": {