@pocketrts/grid 0.4.0 → 0.6.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 +6 -2
- package/dist/costpath.d.ts +37 -0
- package/dist/costpath.js +165 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/march.js +0 -1
- package/dist/regions.d.ts +11 -0
- package/dist/regions.js +40 -0
- package/dist/vision.d.ts +54 -2
- package/dist/vision.js +114 -2
- package/package.json +2 -2
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.
|
|
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, fog of war per side, 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,11 +26,14 @@ 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. |
|
|
32
34
|
| `BucketGrid` | Counting-sort bucket grid rebuilt each step: `build(n, x, y, alive)`, `start` / `items` runs per cell, `cellAt`, `forEachNear(x, y, range, visit)`. |
|
|
33
35
|
| `stampDisc(vis, stamped, w, h, cx, cy, r)` | Reveal a disc of cells; repeated stamps from one cell cost nothing. |
|
|
36
|
+
| `FogOfWar(w, h, sides, side?)` | Fog of war for sides 1 to `sides` (0 = the whole map): `update(vis, version)` takes each side's visible cells once per version and adds them to that side's explored cells; `watch(side)` switches the view; `visible` / `explored` are the viewed side's arrays (a different array after `watch`, so read them through the getters) and `isVisible` / `isExplored` ask about the viewed side; `visibleOf` / `exploredOf` give any side's arrays; `reset()` forgets everything. |
|
|
34
37
|
| `inPolygon(points, x, y)`, `polygonDist(points, x, y)` | Even–odd containment and distance to the outline of a flat `[x0, y0, x1, y1, …]` polygon. |
|
|
35
38
|
| `stepCells`, `ringChain`, `chainLinks`, `chainOutSides` | 8-connected chains (walls, fences): cells between two points, a closed chain through waypoints with loops and extra corner cells removed, which neighbours a chain cell joins, which side of each joined segment faces out. |
|
|
36
39
|
| `lineFormation(units, cx, cy, dx, dy, positions?, options?)`, `FormationUnit`, `Formation`, `FormationOptions`, `DEFAULT_FORMATION_OPTIONS` | Ranks facing a direction: one rank class per rank (lower in front), frontage from the group's footprint (with `taper`, the ranks in front narrower: a wedge); with current positions, members keep their lateral order so paths do not cross. Returns spots, offsets, rank and place per member, and per-rank width, depth, count, radius and slowest speed. |
|
|
@@ -137,9 +140,10 @@ Several sides with different passability (gates that open only for their owner,
|
|
|
137
140
|
|
|
138
141
|
## Notes
|
|
139
142
|
|
|
143
|
+
- 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
144
|
- Flow-field costs are integers in tenths; distances are summed as integers, so results do not depend on float rounding.
|
|
141
145
|
- `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.
|
|
146
|
+
- `LocalPathfinder`, `CostPathfinder`, `BucketGrid` and the flow-field search reuse their buffers: create one per world, or share one when calls never interleave.
|
|
143
147
|
- 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
148
|
- 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
149
|
- `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
|
+
}
|
package/dist/costpath.js
ADDED
|
@@ -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
package/dist/index.js
CHANGED
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;
|
package/dist/regions.js
ADDED
|
@@ -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/dist/vision.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Field of view on a cell raster: each viewer reveals a disc of cells
|
|
3
|
-
* stamped there lets many viewers standing in the same cell cost one stamp.
|
|
2
|
+
* Field of view on a cell raster: each viewer reveals a disc of cells, and a per-cell record of the largest radius
|
|
3
|
+
* already stamped there lets many viewers standing in the same cell cost one stamp. Fog of war keeps, per side, the
|
|
4
|
+
* cells seen now and the cells ever seen, and which side's view is shown.
|
|
4
5
|
*/
|
|
5
6
|
/**
|
|
6
7
|
* Mark the disc of radius `r` cells around cell (cx, cy) in `vis` (set to 1), clipped to the `w` × `h` raster.
|
|
@@ -9,3 +10,54 @@
|
|
|
9
10
|
* `vis` and `stamped` together (fill with 0) before each recomputation.
|
|
10
11
|
*/
|
|
11
12
|
export declare function stampDisc(vis: Uint8Array, stamped: Uint8Array | Uint16Array, w: number, h: number, cx: number, cy: number, r: number): void;
|
|
13
|
+
/**
|
|
14
|
+
* Fog of war for several sides (alliances, or any party with a shared view) on one cell raster: what each side sees now,
|
|
15
|
+
* what each side has ever seen, and the view being shown. Sides are numbered 1 to `sides`; side 0 is the whole-map view,
|
|
16
|
+
* where every cell is visible and explored. The game computes each side's visible cells (with `stampDisc`, say) and hands
|
|
17
|
+
* them in with a version that changes whenever they are recomputed; `update` copies and accumulates them only when the
|
|
18
|
+
* version changes, so calling it every frame is cheap and every reader of one frame sees the same cells.
|
|
19
|
+
*/
|
|
20
|
+
export declare class FogOfWar {
|
|
21
|
+
readonly w: number;
|
|
22
|
+
readonly h: number;
|
|
23
|
+
readonly sides: number;
|
|
24
|
+
/** Cells the side sees now (1 = visible), per side; [0] is the whole map, all 1 */
|
|
25
|
+
private readonly visibleBy;
|
|
26
|
+
/** Cells the side has ever seen (1 = explored), per side; [0] is the whole map, all 1 */
|
|
27
|
+
private readonly exploredBy;
|
|
28
|
+
private viewSide;
|
|
29
|
+
private lastVersion;
|
|
30
|
+
/** All cells start unseen and unexplored, and the view starts on side `side` (default 0, the whole map) */
|
|
31
|
+
constructor(w: number, h: number, sides: number, side?: number);
|
|
32
|
+
/** The side being viewed; 0 = the whole map */
|
|
33
|
+
get side(): number;
|
|
34
|
+
/** The version of the last update, NaN before the first */
|
|
35
|
+
get version(): number;
|
|
36
|
+
/**
|
|
37
|
+
* The viewed side's cells visible now (1 = visible). The array belongs to the side, so `watch` makes this return
|
|
38
|
+
* another array: read it through this getter rather than keeping it. Do not write to it.
|
|
39
|
+
*/
|
|
40
|
+
get visible(): Uint8Array;
|
|
41
|
+
/** The viewed side's explored cells (1 = explored); like `visible`, a different array after `watch`. Do not write to it */
|
|
42
|
+
get explored(): Uint8Array;
|
|
43
|
+
/** Side `side`'s cells visible now, whatever the view; do not write to it */
|
|
44
|
+
visibleOf(side: number): Uint8Array;
|
|
45
|
+
/** Side `side`'s explored cells, whatever the view; do not write to it */
|
|
46
|
+
exploredOf(side: number): Uint8Array;
|
|
47
|
+
/** Show side `side`'s view (0 = the whole map). Every side keeps its own history, so switching loses nothing */
|
|
48
|
+
watch(side: number): void;
|
|
49
|
+
/**
|
|
50
|
+
* Take each side's visible cells: `vis[s]` holds side s's cells (any nonzero = visible, `w` × `h`, row-major) for s
|
|
51
|
+
* from 1 to `sides`; `vis[0]` is ignored. Nothing happens when `version` equals the last update's. Otherwise every
|
|
52
|
+
* side's current cells are replaced and added to its explored cells, whichever side is viewed. Returns whether it
|
|
53
|
+
* took them.
|
|
54
|
+
*/
|
|
55
|
+
update(vis: readonly ArrayLike<number>[], version: number): boolean;
|
|
56
|
+
/** Whether the viewed side sees cell (x, y) now; false outside the raster */
|
|
57
|
+
isVisible(x: number, y: number): boolean;
|
|
58
|
+
/** Whether the viewed side has explored cell (x, y); false outside the raster */
|
|
59
|
+
isExplored(x: number, y: number): boolean;
|
|
60
|
+
/** Forget everything every side has seen and wait for the next update, whatever its version; the view is kept */
|
|
61
|
+
reset(): void;
|
|
62
|
+
private check;
|
|
63
|
+
}
|
package/dist/vision.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Field of view on a cell raster: each viewer reveals a disc of cells
|
|
3
|
-
* stamped there lets many viewers standing in the same cell cost one stamp.
|
|
2
|
+
* Field of view on a cell raster: each viewer reveals a disc of cells, and a per-cell record of the largest radius
|
|
3
|
+
* already stamped there lets many viewers standing in the same cell cost one stamp. Fog of war keeps, per side, the
|
|
4
|
+
* cells seen now and the cells ever seen, and which side's view is shown.
|
|
4
5
|
*/
|
|
5
6
|
/**
|
|
6
7
|
* Mark the disc of radius `r` cells around cell (cx, cy) in `vis` (set to 1), clipped to the `w` × `h` raster.
|
|
@@ -28,3 +29,114 @@ export function stampDisc(vis, stamped, w, h, cx, cy, r) {
|
|
|
28
29
|
vis[row + xx] = 1;
|
|
29
30
|
}
|
|
30
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* Fog of war for several sides (alliances, or any party with a shared view) on one cell raster: what each side sees now,
|
|
34
|
+
* what each side has ever seen, and the view being shown. Sides are numbered 1 to `sides`; side 0 is the whole-map view,
|
|
35
|
+
* where every cell is visible and explored. The game computes each side's visible cells (with `stampDisc`, say) and hands
|
|
36
|
+
* them in with a version that changes whenever they are recomputed; `update` copies and accumulates them only when the
|
|
37
|
+
* version changes, so calling it every frame is cheap and every reader of one frame sees the same cells.
|
|
38
|
+
*/
|
|
39
|
+
export class FogOfWar {
|
|
40
|
+
w;
|
|
41
|
+
h;
|
|
42
|
+
sides;
|
|
43
|
+
/** Cells the side sees now (1 = visible), per side; [0] is the whole map, all 1 */
|
|
44
|
+
visibleBy;
|
|
45
|
+
/** Cells the side has ever seen (1 = explored), per side; [0] is the whole map, all 1 */
|
|
46
|
+
exploredBy;
|
|
47
|
+
viewSide = 0;
|
|
48
|
+
lastVersion = NaN;
|
|
49
|
+
/** All cells start unseen and unexplored, and the view starts on side `side` (default 0, the whole map) */
|
|
50
|
+
constructor(w, h, sides, side = 0) {
|
|
51
|
+
this.w = w;
|
|
52
|
+
this.h = h;
|
|
53
|
+
this.sides = sides;
|
|
54
|
+
if (!Number.isInteger(sides) || sides < 0)
|
|
55
|
+
throw new RangeError(`sides must be a non-negative integer, got ${sides}`);
|
|
56
|
+
const n = w * h, all = new Uint8Array(n).fill(1);
|
|
57
|
+
this.visibleBy = Array.from({ length: sides + 1 }, (_, s) => (s ? new Uint8Array(n) : all));
|
|
58
|
+
this.exploredBy = Array.from({ length: sides + 1 }, (_, s) => (s ? new Uint8Array(n) : all));
|
|
59
|
+
this.watch(side);
|
|
60
|
+
}
|
|
61
|
+
/** The side being viewed; 0 = the whole map */
|
|
62
|
+
get side() {
|
|
63
|
+
return this.viewSide;
|
|
64
|
+
}
|
|
65
|
+
/** The version of the last update, NaN before the first */
|
|
66
|
+
get version() {
|
|
67
|
+
return this.lastVersion;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The viewed side's cells visible now (1 = visible). The array belongs to the side, so `watch` makes this return
|
|
71
|
+
* another array: read it through this getter rather than keeping it. Do not write to it.
|
|
72
|
+
*/
|
|
73
|
+
get visible() {
|
|
74
|
+
return this.visibleBy[this.viewSide];
|
|
75
|
+
}
|
|
76
|
+
/** The viewed side's explored cells (1 = explored); like `visible`, a different array after `watch`. Do not write to it */
|
|
77
|
+
get explored() {
|
|
78
|
+
return this.exploredBy[this.viewSide];
|
|
79
|
+
}
|
|
80
|
+
/** Side `side`'s cells visible now, whatever the view; do not write to it */
|
|
81
|
+
visibleOf(side) {
|
|
82
|
+
return this.visibleBy[this.check(side)];
|
|
83
|
+
}
|
|
84
|
+
/** Side `side`'s explored cells, whatever the view; do not write to it */
|
|
85
|
+
exploredOf(side) {
|
|
86
|
+
return this.exploredBy[this.check(side)];
|
|
87
|
+
}
|
|
88
|
+
/** Show side `side`'s view (0 = the whole map). Every side keeps its own history, so switching loses nothing */
|
|
89
|
+
watch(side) {
|
|
90
|
+
this.viewSide = this.check(side);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Take each side's visible cells: `vis[s]` holds side s's cells (any nonzero = visible, `w` × `h`, row-major) for s
|
|
94
|
+
* from 1 to `sides`; `vis[0]` is ignored. Nothing happens when `version` equals the last update's. Otherwise every
|
|
95
|
+
* side's current cells are replaced and added to its explored cells, whichever side is viewed. Returns whether it
|
|
96
|
+
* took them.
|
|
97
|
+
*/
|
|
98
|
+
update(vis, version) {
|
|
99
|
+
if (version === this.lastVersion)
|
|
100
|
+
return false;
|
|
101
|
+
const n = this.w * this.h;
|
|
102
|
+
if (vis.length < this.sides + 1)
|
|
103
|
+
throw new RangeError(`expected visible cells for sides 1 to ${this.sides}`);
|
|
104
|
+
for (let s = 1; s <= this.sides; s++) {
|
|
105
|
+
if (vis[s].length !== n)
|
|
106
|
+
throw new RangeError(`side ${s}: expected ${n} cells, got ${vis[s].length}`);
|
|
107
|
+
}
|
|
108
|
+
for (let s = 1; s <= this.sides; s++) {
|
|
109
|
+
const src = vis[s], cur = this.visibleBy[s], ex = this.exploredBy[s];
|
|
110
|
+
for (let i = 0; i < n; i++) {
|
|
111
|
+
if (src[i])
|
|
112
|
+
cur[i] = ex[i] = 1;
|
|
113
|
+
else
|
|
114
|
+
cur[i] = 0;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
this.lastVersion = version;
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
/** Whether the viewed side sees cell (x, y) now; false outside the raster */
|
|
121
|
+
isVisible(x, y) {
|
|
122
|
+
return x >= 0 && y >= 0 && x < this.w && y < this.h && this.visible[y * this.w + x] === 1;
|
|
123
|
+
}
|
|
124
|
+
/** Whether the viewed side has explored cell (x, y); false outside the raster */
|
|
125
|
+
isExplored(x, y) {
|
|
126
|
+
return x >= 0 && y >= 0 && x < this.w && y < this.h && this.explored[y * this.w + x] === 1;
|
|
127
|
+
}
|
|
128
|
+
/** Forget everything every side has seen and wait for the next update, whatever its version; the view is kept */
|
|
129
|
+
reset() {
|
|
130
|
+
for (let s = 1; s <= this.sides; s++) {
|
|
131
|
+
this.visibleBy[s].fill(0);
|
|
132
|
+
this.exploredBy[s].fill(0);
|
|
133
|
+
}
|
|
134
|
+
this.lastVersion = NaN;
|
|
135
|
+
}
|
|
136
|
+
check(side) {
|
|
137
|
+
if (!Number.isInteger(side) || side < 0 || side > this.sides) {
|
|
138
|
+
throw new RangeError(`side must be an integer from 0 to ${this.sides}, got ${side}`);
|
|
139
|
+
}
|
|
140
|
+
return side;
|
|
141
|
+
}
|
|
142
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pocketrts/grid",
|
|
3
|
-
"version": "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.6.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, fog of war per side, polygons, cell chains, line formations and column march",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Junjie Bai <bjj19851010@gmail.com>",
|
|
7
7
|
"repository": {
|