@pocketrts/grid 0.3.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,13 +139,21 @@ 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
- - `MarchRules.flank` (default off) also keeps ranks clear of an obstacle on one side and of thin obstacles, counts a thin wall that runs on across the column's width as a narrow place, and lets the column turn as tightly as half the usable width where the way is narrower than the column: turn it on where routes run along walls.
146
- - `MarchRules.faceRoute`, `wheel` and `lookClear` (all off by default) are for rigid formations on routes that hug walls: `faceRoute` forms the column up along the route's first stretch instead of the straight line to the goal, `wheel` makes only the ranks on a bend close up along the trail, and `lookClear` straightens the route toward points that keep clear of walls to each side. With all of them off, the march is exactly the one Pocket War ships (its state checksums are byte-identical on the package).
147
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.
148
149
  - The result objects `STEER`, `MARCH_SLOT`, `MARCH_FOLLOW` and `MARCH_POINT` are shared and overwritten by each call: copy what is needed before the next one.
149
150
  - As for flow fields, the outermost ring of the grid must be blocked.
151
+
152
+ ## Upgrading the march from 0.3 to 0.4
153
+
154
+ Start with `marchRules(cellSize / 32)`. The column forms up along the route, keeps clearance beside walls and closes its ranks around bends. Members walk back toward reachable places after a reversal. A member cut off from both its place and its rank follows its own route at the supplied run speed.
155
+
156
+ - Remove `flank`, `faceRoute`, `wheel`, `lookClear`, `waitAhead` and `apartTrail` from rule objects. Drop copied values for `lookMin`, `axisFrom` and `axisFull` to inherit the defaults of ten cells, 0.5 and 0.3. Keep explicit overrides where the map or game uses different tuning.
157
+ - For games that let members advance along their own routes during combat, set `pushAhead` to the distance in world units a member must be ahead of its place to receive `STEER_PUSH` while the group is opposed. The default is `Infinity`.
158
+ - For subcell passages such as diagonal bridges, keep the map's world-space movement queries and optional `crossSection` measurements. They supply the physical boundaries of the passage.
159
+ - March trajectories and checksums change with this version. Pin the same grid version on every peer in a lockstep match and replay recordings with the version that produced them.
@@ -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.d.ts CHANGED
@@ -62,7 +62,7 @@ export declare const STEER: {
62
62
  * What `steerMember` returns:
63
63
  * - `STEER_IDLE`: the group is not marching in ranks right now; the member moves as if it had no march.
64
64
  * - `STEER_LEAVE`: the member has left the march (the game clears its membership) and makes for its own spot.
65
- * - `STEER_PUSH`: the member stays in the march but walks on along its route instead of waiting for its place.
65
+ * - `STEER_PUSH`: the member stays in the march but walks on along its route while the group is opposed.
66
66
  * - `STEER_APART`: the member finds its own way along its route at `STEER.speed`, and rejoins when it can.
67
67
  * - `STEER_KEEP`: the member keeps its place: it moves at (`STEER.vx`, `STEER.vy`).
68
68
  */
package/dist/march.js CHANGED
@@ -78,17 +78,14 @@ export function createMarch(marches, gr, M, order) {
78
78
  Object.assign(g, {
79
79
  alive: true, layer, destX, destY, destCell,
80
80
  speed, run, hold, engaged: 0, free: 0, cEngaged: 0, cFree: 0, cOpposed: 0, fx, fy, arrived: false, blocked: false, loose: false, opposedT: 0, n,
81
- cnt: 0, lagSum: 0, lagApart: 0, over: 0, sx: 0, sy: 0, cap, width, depth, open: M.flank ? width + big : width / 2 + big, ahead, rows, tail: false, tailT: 0,
81
+ cnt: 0, lagSum: 0, lagApart: 0, over: 0, sx: 0, sy: 0, cap, width, depth, open: width + big, ahead, rows, tail: false, tailT: 0,
82
82
  });
83
83
  anchor(gr, g, M, x, y, false);
84
84
  return g;
85
85
  }
86
86
  /**
87
- * Form up (on an order, after an engagement, when the route is cut): lay the trail out straight behind the front
88
- * rank against the direction to the goal, and let the probe walk out its lead from the front rank at once. With
89
- * `MarchRules.faceRoute` the direction is that of the route's first stretch, and a column forming up round its
90
- * centre (`front` false) is laid out along the route instead: the straight trail lies behind the place of its rear,
91
- * the probe walks one column depth further than its lead, and the front rank stands that much on along its way.
87
+ * Lay the column along the route, beginning at the rear when forming around a centre. The probe walks out
88
+ * one column depth plus its lead so the front rank starts one depth along the walkable route.
92
89
  * @param x, y The centre of the group (`front` false: the column forms up round it, the front rank at its front), or
93
90
  * the front rank's position (`front` true).
94
91
  */
@@ -102,7 +99,7 @@ function anchor(gr, g, M, x, y, front) {
102
99
  }
103
100
  const dx = g.destX - x, dy = g.destY - y, dl = dmath.hypot(dx, dy) || 1;
104
101
  let hx = dx / dl, hy = dy / dl;
105
- if (M.faceRoute && gr.lineBlocked(x, y, g.destX, g.destY)) {
102
+ if (gr.lineBlocked(x, y, g.destX, g.destY)) {
106
103
  // The route does not set off straight for the goal: face the furthest point in sight along it. A route still
107
104
  // being searched is finished on the spot, as for a new route
108
105
  const f = gr.field(g.destCell);
@@ -116,9 +113,8 @@ function anchor(gr, g, M, x, y, front) {
116
113
  }
117
114
  }
118
115
  }
119
- // With `faceRoute`: how far along the route the column is laid out when forming up round the centre
120
116
  let along = 0;
121
- if (!front && M.faceRoute) {
117
+ if (!front) {
122
118
  // The column forms up along the route: its rear as far behind the centre as there is room for (at most half its
123
119
  // depth), and from there one column depth on along the way the probe walks. Laid out straight round the centre
124
120
  // instead, the ranks of a column that forms up in a cramped place, or whose route sets off round a corner, would
@@ -132,15 +128,6 @@ function anchor(gr, g, M, x, y, front) {
132
128
  }
133
129
  along = g.depth;
134
130
  }
135
- else if (!front) {
136
- // The front rank at the front of the column (where it can walk there): the column then stands round the centre
137
- const fwd = Math.min(g.depth / 2, dl - M.scale);
138
- const lx = x + hx * fwd, ly = y + hy * fwd;
139
- if (fwd > 0 && !(gr.probeBlocked?.(x, y, lx, ly) ?? gr.blocked(gr.cellAt(lx, ly))) && !gr.lineBlocked(x, y, lx, ly)) {
140
- x = lx;
141
- y = ly;
142
- }
143
- }
144
131
  layTrail(g, M, x, y, hx, hy);
145
132
  Object.assign(g, {
146
133
  x, y, hx, hy, px: x, py: y, phx: hx, phy: hy, head: 0, rec: 0, v: 0, lag: M.lagStop,
@@ -203,15 +190,15 @@ function placeFront(g, M) {
203
190
  g.hy = TP.hy;
204
191
  }
205
192
  const AIM = { x: 0, y: 0 };
206
- /** The width of the way at the probe as far as it is known: with `flank`, the usable width at the newest trail point where that is less than the column's. */
193
+ /** The width of the way at the probe as far as it is known: the usable width at the newest trail point where that is less than the column's. */
207
194
  function wayAt(g, M) {
208
- return M.flank ? Math.min(g.width, widthAt(g, M, 0)) : g.width;
195
+ return Math.min(g.width, widthAt(g, M, 0));
209
196
  }
210
197
  /**
211
198
  * Count cells along the flow field from under the probe and take the furthest one a straight walk reaches (no
212
199
  * further than the look-ahead distance), into `AIM`. A flow field has eight directions; walked as it is, the route
213
- * is a polyline, and a rank following it would wheel at every kink. With `MarchRules.lookClear` the furthest cell
214
- * the walk to which is also clear that share of the column's width to each side is taken when there is one, so the
200
+ * is a polyline, and a rank following it would wheel at every kink. The furthest cell
201
+ * with a straight walk clear for a quarter of the usable width to each side is taken when there is one, so the
215
202
  * straightened route keeps its distance from the corners it goes round.
216
203
  * @param laid False while forming up, before the trail is laid out: no usable width is known yet.
217
204
  */
@@ -219,10 +206,7 @@ function lookAhead(gr, g, M, f, cell, x = g.px, y = g.py, laid = true) {
219
206
  const mw = gr.w, T = gr.cellSize;
220
207
  const look = Math.max(M.lookMin, g.width * M.lookK);
221
208
  const max = Math.ceil(look / T) * 2 + 2;
222
- // With `lookClear` a point the walk to which is also clear to each side is preferred to a further one that is only
223
- // just in sight: a line of sight that only just passes a corner would lead the column along the corner's wall, to
224
- // turn round the corner on the spot
225
- const side = M.lookClear > 0 ? (laid ? wayAt(g, M) : g.width) * M.lookClear : 0;
209
+ const side = (laid ? wayAt(g, M) : g.width) / 4;
226
210
  let c = cell, ok = false, wide = false;
227
211
  // A real passage can overlap a blocked cell with no flow direction. Rejoin the field through a visible
228
212
  // neighbour; its centre remains the aim if the following bend hides every point further down the route.
@@ -354,8 +338,7 @@ function probeMove(gr, g, M, dist, vref) {
354
338
  da -= Math.PI * 2;
355
339
  else if (da < -Math.PI)
356
340
  da += Math.PI * 2;
357
- // With `flank` the usable width is known all along the route: where the way is narrower than the column, the
358
- // squeezed ranks can wheel as tightly as the way is wide
341
+ // Squeezed ranks can turn as tightly as the passage allows.
359
342
  const way = wayAt(g, M);
360
343
  const radius = dd < g.width ? M.scale : Math.max(M.turnR, way / 2);
361
344
  let turn = step / radius;
@@ -435,7 +418,6 @@ function paceTop(g, M) {
435
418
  rowsAt(g, M, g.lead - M.scale, TB, TL, TE, TW);
436
419
  let fold = 1, foldRun = Infinity;
437
420
  for (let r = 0; r < g.rows; r++) {
438
- // Kept in this order, not as (rowE − TE) / scale: with scale 1 the grouping decides the last bit of the result
439
421
  g.rowK[r] = 1 + g.rowE[r] / M.scale - TE[r] / M.scale;
440
422
  const fr = g.rowLen[r] / g.rowD[r];
441
423
  if (fr > 1 && g.rowRun[r] < foldRun)
@@ -448,11 +430,11 @@ function paceTop(g, M) {
448
430
  top += (foldRun * M.trot - top) * smooth(fold - 1);
449
431
  for (let r = 0; r < g.rows; r++) {
450
432
  let kr = g.rowK[r];
451
- // With `wheel` it is the outermost place of the rank that must keep within the rank's speed. A rank on a bend
433
+ // The outermost place must keep within the rank's speed. A rank on a bend
452
434
  // with the front rank past it moves that much less along the trail (it closes up), so the two cancel; a front
453
435
  // rank on a bend itself is what this slows down. Not within one width of the goal: there the probe turned as
454
436
  // sharply as it took to reach the goal, and the members are about to leave for their own spots
455
- if (M.wheel && !(g.pDone && g.lead < g.width))
437
+ if (!(g.pDone && g.lead < g.width))
456
438
  kr *= TW[r];
457
439
  if (kr <= 1)
458
440
  continue;
@@ -495,6 +477,7 @@ function tally(marches, grounds, mem, M, dt) {
495
477
  g.cnt = g.lagSum = g.lagApart = g.over = g.cEngaged = g.cFree = g.cOpposed = g.sx = g.sy = 0;
496
478
  // Each march's ground, asked for once per tally
497
479
  const grs = [];
480
+ const ahead = [];
498
481
  for (let i = 0; i < mem.n; i++) {
499
482
  const gi = mem.march(i);
500
483
  if (gi < 0 || !mem.alive(i))
@@ -524,15 +507,13 @@ function tally(marches, grounds, mem, M, dt) {
524
507
  if (!gr.standable(SLOT.x, SLOT.y) || gr.lineBlocked(SLOT.cx, SLOT.cy, SLOT.x, SLOT.y))
525
508
  g.over++;
526
509
  const ox = SLOT.x - mem.x(i), oy = SLOT.y - mem.y(i);
527
- // A member whose place is behind it does not lag: it waits for the place, or walks on while the group is opposed;
528
- // either way the front rank need not wait
529
- if (ox * SLOT.hx + oy * SLOT.hy < -M.waitAhead)
530
- continue;
531
- const lag = Math.sqrt(ox * ox + oy * oy);
510
+ // A later member may be the one in combat. Set aside the lag of potential pushers until everyone is counted.
511
+ const sum = ox * SLOT.hx + oy * SLOT.hy < -M.pushAhead ? ahead[gi] ??= { lagSum: 0, lagApart: 0 } : g;
512
+ const lag = Math.min(Math.sqrt(ox * ox + oy * oy), M.lagCap);
532
513
  if (mem.apart(i))
533
- g.lagApart += lag > M.lagCap ? M.lagCap : lag;
514
+ sum.lagApart += lag;
534
515
  else
535
- g.lagSum += lag > M.lagCap ? M.lagCap : lag;
516
+ sum.lagSum += lag;
536
517
  }
537
518
  for (const g of marches) {
538
519
  if (!g.alive)
@@ -541,6 +522,15 @@ function tally(marches, grounds, mem, M, dt) {
541
522
  if (!g.cnt)
542
523
  g.alive = false;
543
524
  else {
525
+ if (g.cOpposed > 0)
526
+ g.opposedT = M.opposedLinger;
527
+ else if (g.opposedT > 0)
528
+ g.opposedT -= dt * TALLY;
529
+ const pushing = ahead[g.id];
530
+ if (pushing && g.opposedT <= 0) {
531
+ g.lagSum += pushing.lagSum;
532
+ g.lagApart += pushing.lagApart;
533
+ }
544
534
  // While the column is draped over an obstacle, members out of reach of their places are finding their own way
545
535
  // and the front rank does not wait for them: waiting would hold the ranks behind on this side of the obstacle
546
536
  // too, and the group would pass it one rank at a time. Once the whole column is clear they count again, and the
@@ -551,12 +541,6 @@ function tally(marches, grounds, mem, M, dt) {
551
541
  g.free = g.cFree / g.cnt;
552
542
  // Engaged: break ranks. Afterwards the group forms up round where its members are now; it does not walk back
553
543
  const loose = (g.hold && g.engaged > M.holdEngaged) || g.free > 0.5;
554
- // Counted down by the tally interval, so a lone opponent appearing and gone again does not send the group
555
- // forward and straight back to waiting for places
556
- if (g.cOpposed > 0)
557
- g.opposedT = M.opposedLinger;
558
- else if (g.opposedT > 0)
559
- g.opposedT -= dt * TALLY;
560
544
  if (g.loose && !loose && !g.arrived)
561
545
  anchor(grounds(g.layer), g, M, g.sx / g.cnt, g.sy / g.cnt, false);
562
546
  g.loose = loose;
@@ -652,7 +636,7 @@ export const STEER = { vx: 0, vy: 0, set: false, speed: 0, apart: false };
652
636
  * What `steerMember` returns:
653
637
  * - `STEER_IDLE`: the group is not marching in ranks right now; the member moves as if it had no march.
654
638
  * - `STEER_LEAVE`: the member has left the march (the game clears its membership) and makes for its own spot.
655
- * - `STEER_PUSH`: the member stays in the march but walks on along its route instead of waiting for its place.
639
+ * - `STEER_PUSH`: the member stays in the march but walks on along its route while the group is opposed.
656
640
  * - `STEER_APART`: the member finds its own way along its route at `STEER.speed`, and rejoins when it can.
657
641
  * - `STEER_KEEP`: the member keeps its place: it moves at (`STEER.vx`, `STEER.vy`).
658
642
  */
@@ -674,14 +658,10 @@ export function steerMember(gr, g, M, row, col, lateral, ux, uy, destX, destY, s
674
658
  if (g.blocked || g.loose || free)
675
659
  return STEER_IDLE;
676
660
  marchSlot(g, M, row, col, lateral);
677
- // Whether the place is behind the member, measured along the column's direction of travel there
678
- const behind = (SLOT.x - ux) * SLOT.hx + (SLOT.y - uy) * SLOT.hy < -M.waitAhead;
679
661
  // Winding up: the rank has passed the goal, or no narrow place lies ahead and the spot is in sight
680
662
  if (g.tail && marchRelease(gr, g, ux, uy, destX, destY))
681
663
  return STEER_LEAVE;
682
- // The place is behind and the group is opposed: do not wait for it. Whether the place is in reach does not matter
683
- // (past an obstacle it often is not), and there is nothing to catch up with: the member is ahead of its place
684
- if (behind && g.opposedT > 0)
664
+ if (g.opposedT > 0 && (SLOT.x - ux) * SLOT.hx + (SLOT.y - uy) * SLOT.hy < -M.pushAhead)
685
665
  return STEER_PUSH;
686
666
  const mode = marchFollow(gr, ux, uy);
687
667
  if (mode !== FOLLOW_SLOT)
@@ -690,24 +670,13 @@ export function steerMember(gr, g, M, row, col, lateral, ux, uy, destX, destY, s
690
670
  if (mode === FOLLOW_APART && g.tail)
691
671
  return STEER_LEAVE;
692
672
  if (mode === FOLLOW_APART) {
693
- // Out of reach of the place and the rank: do not wait, find a way round and fall in afterwards. Run to catch up
694
- // with a place ahead; with the place behind, move at the rank's pace instead of running ahead to stand and wait
695
- if (!behind)
696
- STEER.speed = run;
697
- else {
698
- const v = Math.max(SLOT.v, speed * M.apartTrail);
699
- STEER.speed = v < run ? v : run;
700
- }
673
+ STEER.speed = run;
701
674
  return STEER_APART;
702
675
  }
703
676
  // Aim a little ahead of the point to follow: on its place the member moves at its rank's pace, behind it runs
704
677
  const ex = FOLLOW.x + SLOT.hx * SLOT.v * M.leadTime - ux, ey = FOLLOW.y + SLOT.hy * SLOT.v * M.leadTime - uy;
705
678
  const ed = Math.sqrt(ex * ex + ey * ey);
706
- if (behind) {
707
- // The place is behind (the member got ahead on a detour): stand and wait for it, do not walk back
708
- STEER.set = true;
709
- }
710
- else if (ed > 0.5 * M.scale) {
679
+ if (ed > 0.5 * M.scale) {
711
680
  let v = ed / M.leadTime;
712
681
  if (v > run)
713
682
  v = run;
@@ -2,7 +2,7 @@
2
2
  * Column march: measuring a narrow place. At a point of the trail, find the shortest cross-section with a large
3
3
  * obstacle on both sides, each blocking its whole wing, and give the usable width on each side and the direction of
4
4
  * the cross-section. A place with an obstacle on one side only, or one that leaves the wing tip free (the wings can
5
- * pass round it), is not a narrow place. With `MarchRules.flank`, a long wall blocks its wing however thin it is, and
5
+ * pass round it), is not a narrow place. A long wall blocks its wing however thin it is, and
6
6
  * where no narrow place is found, what stands beside the route is still recorded, side by side, so that ranks keep
7
7
  * clear of it.
8
8
  */
@@ -20,8 +20,8 @@ export declare function chokeClear(g: March): void;
20
20
  /**
21
21
  * Measure the narrow place at trail point (x, y), travelling in direction (tx, ty); the result goes to `CHOKE`. Among
22
22
  * four fixed directions, take the shortest line not parallel to the travel that hits a large obstacle both ways as
23
- * the cross-section: it follows the opening (parallel to the wall), not the heading of the column. Nothing found
24
- * leaves `CHOKE` as `chokeClear` sets it (but see `MarchRules.flank`). The widths are less the clearance `chokePad`,
23
+ * the cross-section: it follows the opening (parallel to the wall), not the heading of the column. Without such a line,
24
+ * each side still records its own clearance. The widths are less the clearance `chokePad`,
25
25
  * and at a narrow place add up to less than `narrow` times the column's width.
26
26
  */
27
27
  export declare function chokeAt(gr: MarchGround, g: March, M: MarchRules, x: number, y: number, tx: number, ty: number): void;
@@ -59,7 +59,7 @@ function rayHit(gr, x, y, dx, dy, max) {
59
59
  * Distance from the trail point (x, y) along (dx, dy) to an obstacle; −1 when the obstacle does not block this whole
60
60
  * wing: it must run on from where it was hit out to the wing tip (half the column's width, at least `chokeMin`).
61
61
  * It is sampled every half cell, the first sample a quarter cell in, so every cell is looked at twice and a gap one
62
- * cell wide is not missed. With `MarchRules.flank`, an obstacle thinner than that still counts when it is a wall
62
+ * cell wide is not missed. An obstacle thinner than that still counts when it is a wall
63
63
  * (`wallRuns`): otherwise a corridor between thin walls is not measured across, only along a diagonal where the
64
64
  * walls happen to be thick enough, and passes for as wide as that diagonal is long.
65
65
  */
@@ -72,7 +72,7 @@ function wallAt(gr, g, M, x, y, dx, dy) {
72
72
  for (let k = T / 4; k <= run; k += T / 2) {
73
73
  const px = x + dx * (d + k), py = y + dy * (d + k);
74
74
  if (!solidCell(gr, Math.floor(px / T), Math.floor(py / T)))
75
- return M.flank && wallRuns(gr, g, M, x + dx * (d + T / 2), y + dy * (d + T / 2), -dy, dx) ? d : -1;
75
+ return wallRuns(gr, g, M, x + dx * (d + T / 2), y + dy * (d + T / 2), -dy, dx) ? d : -1;
76
76
  }
77
77
  return d;
78
78
  }
@@ -100,8 +100,8 @@ function wallRuns(gr, g, M, x, y, ux, uy) {
100
100
  /**
101
101
  * Measure the narrow place at trail point (x, y), travelling in direction (tx, ty); the result goes to `CHOKE`. Among
102
102
  * four fixed directions, take the shortest line not parallel to the travel that hits a large obstacle both ways as
103
- * the cross-section: it follows the opening (parallel to the wall), not the heading of the column. Nothing found
104
- * leaves `CHOKE` as `chokeClear` sets it (but see `MarchRules.flank`). The widths are less the clearance `chokePad`,
103
+ * the cross-section: it follows the opening (parallel to the wall), not the heading of the column. Without such a line,
104
+ * each side still records its own clearance. The widths are less the clearance `chokePad`,
105
105
  * and at a narrow place add up to less than `narrow` times the column's width.
106
106
  */
107
107
  export function chokeAt(gr, g, M, x, y, tx, ty) {
@@ -114,9 +114,8 @@ export function chokeAt(gr, g, M, x, y, tx, ty) {
114
114
  if (r === Infinity && l === Infinity)
115
115
  return;
116
116
  // An unbounded wing has room for a whole rank to shift away from the other edge.
117
- const unbounded = M.flank ? g.open : g.open + g.width / 2;
118
- CHOKE.R = r === Infinity ? unbounded : Math.max(0, r - M.chokePad);
119
- CHOKE.L = l === Infinity ? unbounded : Math.max(0, l - M.chokePad);
117
+ CHOKE.R = r === Infinity ? g.open : Math.max(0, r - M.chokePad);
118
+ CHOKE.L = l === Infinity ? g.open : Math.max(0, l - M.chokePad);
120
119
  if (r + l >= g.width * M.narrow)
121
120
  return;
122
121
  CHOKE.ax = forward ? axisX : -axisX;
@@ -146,9 +145,9 @@ export function chokeAt(gr, g, M, x, y, tx, ty) {
146
145
  CHOKE.has = 1;
147
146
  }
148
147
  // A point on a solid cell measures nothing either way (a ray from it would read 0 on both sides)
149
- if (CHOKE.has || !M.flank || solidCell(gr, Math.floor(x / gr.cellSize), Math.floor(y / gr.cellSize)))
148
+ if (CHOKE.has || solidCell(gr, Math.floor(x / gr.cellSize), Math.floor(y / gr.cellSize)))
150
149
  return;
151
- // No narrow place by that measure. With `flank`, whatever stands within the column's width square to the travel
150
+ // Without a narrow place, whatever stands within the column's width square to the travel
152
151
  // still counts on its own side: no direction of a narrow place goes with it, so ranks stay square to their heading
153
152
  const dr = rayHit(gr, x, y, -ty, tx, g.width), dl = rayHit(gr, x, y, ty, -tx, g.width);
154
153
  if (dr >= 0)
@@ -3,8 +3,7 @@ import type { March, MarchGround, MarchRules } from './marchTypes.js';
3
3
  * Where each rank stands with the front rank `b` behind the probe: from the front rank back, one after another, each
4
4
  * taking the stretch `rowLength` gives. Results go to `rb` (distance of the rank's middle behind the probe), `rl`
5
5
  * (length of its stretch), `re` (how much further back it is than unfolded) and, when given, `wh` (how much further
6
- * the rank's outermost place moves than its point on the trail, averaged over its stretch: 1 without
7
- * `MarchRules.wheel`).
6
+ * the rank's outermost place moves than its point on the trail, averaged over its stretch).
8
7
  */
9
8
  export declare function rowsAt(g: March, M: MarchRules, b: number, rb: Float64Array, rl: Float64Array, re: Float64Array, wh?: Float64Array): void;
10
9
  /**
@@ -29,14 +29,14 @@ function wheelAt(g, M, r, b) {
29
29
  const lo = half - L, hi = R - half, sh = lo > hi ? (R - L) / 2 : lo > 0 ? lo : hi < 0 ? hi : 0;
30
30
  return 1 + turn / (2 * d) * ((sh < 0 ? -sh : sh) + half);
31
31
  }
32
- /** Set by `rowLength`: the rank's wheel factor (`wheelAt`), averaged over the stretch it takes; exactly 1 where no piece of it has a factor above 1, and without `MarchRules.wheel`. */
32
+ /** Set by `rowLength`: the rank's wheel factor (`wheelAt`), averaged over the stretch it takes; exactly 1 where no piece of it has a factor above 1. */
33
33
  let WHEEL = 1;
34
34
  /**
35
35
  * How long a stretch of trail rank r takes back from its leading edge `edge` (distance behind the probe). Each piece
36
36
  * counts for "usable width ÷ rank width" of its length (at most 1, at least 1 / `stretchMax`) towards one rank depth.
37
37
  * Where the way is wide enough a piece counts whole, so in the open the stretch is exactly one rank depth; where the
38
38
  * way is a fraction of the rank's width the stretch is that many times longer, up to `stretchMax`. The length of a
39
- * long folded rank changes smoothly across a change of width, without a jump. With `MarchRules.wheel` a piece on a
39
+ * long folded rank changes smoothly across a change of width, without a jump. A piece on a
40
40
  * bend counts for more, by as much as the rank's outermost place moves further than its point on the trail: the
41
41
  * stretch is shorter there, and ranks pass a bend closed up along the trail.
42
42
  */
@@ -44,8 +44,8 @@ function rowLength(g, M, r, edge) {
44
44
  const d = g.rowD[r], rw = g.rowW[r], pad = g.rowRad[r] * 2;
45
45
  const lo = 1 / M.stretchMax, piece = ROW_STEP * M.scale;
46
46
  let acc = 0, len = 0, squeezed = false;
47
- // For `wheel`: the wheel factor of each piece times its length, summed, and whether any piece had one above 1
48
- let turned = 0, w = 1, bent = false;
47
+ // The wheel factor of each piece times its length, summed, and whether any piece had one above 1
48
+ let turned = 0, bent = false;
49
49
  WHEEL = 1;
50
50
  for (;;) {
51
51
  const q = (d - acc) * (squeezed ? 1 / lo : 1);
@@ -63,16 +63,13 @@ function rowLength(g, M, r, edge) {
63
63
  if (f < lo)
64
64
  f = lo;
65
65
  }
66
- if (M.wheel) {
67
- // On a bend the ranks keep their distance along the outside of it: along the trail they close up
68
- w = wheelAt(g, M, r, edge + len + step / 2);
69
- if (w > 1) {
70
- f *= w;
71
- squeezed = bent = true;
72
- }
73
- else
74
- w = 1;
66
+ let w = wheelAt(g, M, r, edge + len + step / 2);
67
+ if (w > 1) {
68
+ f *= w;
69
+ squeezed = bent = true;
75
70
  }
71
+ else
72
+ w = 1;
76
73
  if (acc + f * step >= d) {
77
74
  // Wide enough all the way: exactly one rank depth, with no accumulated rounding, so in the open the column is
78
75
  // bit for bit the formation it was made from
@@ -90,8 +87,7 @@ function rowLength(g, M, r, edge) {
90
87
  * Where each rank stands with the front rank `b` behind the probe: from the front rank back, one after another, each
91
88
  * taking the stretch `rowLength` gives. Results go to `rb` (distance of the rank's middle behind the probe), `rl`
92
89
  * (length of its stretch), `re` (how much further back it is than unfolded) and, when given, `wh` (how much further
93
- * the rank's outermost place moves than its point on the trail, averaged over its stretch: 1 without
94
- * `MarchRules.wheel`).
90
+ * the rank's outermost place moves than its point on the trail, averaged over its stretch).
95
91
  */
96
92
  export function rowsAt(g, M, b, rb, rl, re, wh) {
97
93
  let extra = 0;
@@ -127,13 +123,9 @@ export const SLOT = { x: 0, y: 0, hx: 0, hy: 0, cx: 0, cy: 0, b: 0, l: 0, half:
127
123
  */
128
124
  export function marchSlot(g, M, r, c, l) {
129
125
  const rw = g.rowW[r], sp = g.rowSp[r], len = g.rowLen[r];
130
- // How many short ranks the rank folds into. With `wheel` the stretch is also shorter on a bend, so the folding is
131
- // taken from the usable width at the rank's middle instead
132
- let m = len / g.rowD[r];
133
- if (M.wheel) {
134
- const fw = (widthAt(g, M, g.rowB[r]) - g.rowRad[r] * 2) / rw;
135
- m = fw >= 1 ? 1 : fw * M.stretchMax < 1 ? M.stretchMax : 1 / fw;
136
- }
126
+ // The stretch shortens on bends, so only the usable width at the rank's middle determines folding.
127
+ const fw = (widthAt(g, M, g.rowB[r]) - g.rowRad[r] * 2) / rw;
128
+ const m = fw >= 1 ? 1 : fw * M.stretchMax < 1 ? M.stretchMax : 1 / fw;
137
129
  const E = M.foldEase;
138
130
  let ph = 0, dc = 0;
139
131
  for (let k = 0, p2 = 1; k < 7 && p2 < m; k++, p2 *= 2) {
@@ -27,15 +27,15 @@ export interface MarchRules {
27
27
  lagStop: number;
28
28
  /** The most one member counts for in that average. Default 400. */
29
29
  lagCap: number;
30
- /** A member whose place has dropped this far behind it (it got ahead on a detour) stands and waits instead of walking back. Default 14. */
31
- waitAhead: number;
30
+ /** While opposed, members this far ahead of their place may push on along their own route. Infinity keeps them in formation. */
31
+ pushAhead: number;
32
32
  /** The most the probe's heading (the direction the ranks face) turns per second. Default 1.4. */
33
33
  turn: number;
34
- /** The column's turning radius is half its width, and at least this; unlimited within one width of the goal. Default 40. */
34
+ /** The column's turning radius is half its usable width, and at least this; unlimited within one width of the goal. Default 40. */
35
35
  turnR: number;
36
36
  /** While the heading still turns, the probe may walk at most this far off it, so the ranks sidestep onto the route. Default 0.6. */
37
37
  slide: number;
38
- /** How far the probe looks along the route to straighten it: width × `lookK`, at least `lookMin`. Defaults 0.75, 96. */
38
+ /** How far the probe looks along the route to straighten it: width × `lookK`, at least `lookMin`. Defaults 0.75, 320. */
39
39
  lookK: number;
40
40
  lookMin: number;
41
41
  /** The probe leads the front rank by the distance the ranks need to narrow from full width to nothing, plus this. Default 48. */
@@ -57,15 +57,13 @@ export interface MarchRules {
57
57
  narrow: number;
58
58
  /** The most a rank stretches along the trail in a narrow place; narrower still, its members close up sideways. Default 4. */
59
59
  stretchMax: number;
60
- /** A rank's cross-section starts turning from square to the column towards the direction of the narrow place when the usable width drops below `axisFrom` of the column's width, and follows it fully at `axisFull`. Defaults 0.75, 0.5. */
60
+ /** A rank's cross-section starts turning from square to the column towards the direction of the narrow place when the usable width drops below `axisFrom` of the column's width, and follows it fully at `axisFull`. Defaults 0.5, 0.3. */
61
61
  axisFrom: number;
62
62
  axisFull: number;
63
63
  /** Each fold of a rank first staggers members front to back, then closes them up sideways; each takes this share of a doubling of the stretch. Default 0.3. */
64
64
  foldEase: number;
65
65
  /** No rank is asked for more than this share of its slowest member's full speed; a column with folded ranks moves up to that. Default 0.88. */
66
66
  trot: number;
67
- /** A member that finds its own way while its place is behind it moves at its rank's pace, and at least this share of its own speed. Default 0.3. */
68
- apartTrail: number;
69
67
  /** A new route keeps the column when the cosine between its first direction and the front rank's heading is at least this (0 = up to a right angle); otherwise the group forms up again. Default 0. */
70
68
  rerouteCos: number;
71
69
  /** After the front rank arrives, the column keeps leading ranks through a narrow place for at most this many seconds. Default 20. */
@@ -74,42 +72,6 @@ export interface MarchRules {
74
72
  opposedLinger: number;
75
73
  /** A member aims at where its place will be this many seconds from now, so it settles at its rank's pace. Default 0.4. */
76
74
  leadTime: number;
77
- /**
78
- * Also keep clear of an obstacle on one side of the route only, and of obstacles too thin to block a whole wing:
79
- * the ranks move over to the open side, or close up between two such obstacles; a wall that runs on for half the
80
- * column's width or more makes a narrow place however thin it is, so a corridor between thin walls is measured
81
- * straight across; and where the way is narrower than the column, the column turns as tightly as half the way's
82
- * width instead of half its own. Default false: only a place with a large obstacle on both sides narrows the
83
- * column; elsewhere members whose places are cut off close in towards their rank's middle on their own, which
84
- * crowds them when the route runs right along a wall.
85
- */
86
- flank: boolean;
87
- /**
88
- * Form up along the route: facing the way it sets off (the furthest point in sight along it), the rear rank as far
89
- * behind the group's centre as there is room for (at most half the column's depth), and the ranks ahead of it
90
- * along the way the probe walks. A route still being searched is finished on the spot for it, whatever the flow
91
- * fields' budget. Default false: the column forms up in a straight line round the centre, facing the goal; a
92
- * column whose route sets off round an obstacle then wheels onto it as it sets off, and one that forms up in a
93
- * cramped place has ranks whose places are in or behind a wall.
94
- */
95
- faceRoute: boolean;
96
- /**
97
- * Wheel in turn: on a bend each rank moves at the pace at which its outermost place keeps the column's speed, as
98
- * the inner flank of a wheeling line shortens its step for the outer one. Along the trail the ranks on the bend
99
- * close up; the ranks before it march up at the column's pace and the ranks past it march on at it. The front
100
- * rank slows only while it is on a bend itself. Default false: every rank keeps the column's pace along the trail
101
- * through a bend, the members on the outside of it fall behind their places and catch up on the next straight
102
- * stretch.
103
- */
104
- wheel: boolean;
105
- /**
106
- * When straightening the route, prefer a point the walk to which is clear this share of the column's width to
107
- * each side (with `flank`, of the usable width where that is less) to a further one that is only just in sight
108
- * past a corner. For routes that keep their distance from walls (a game that charges for ground near obstacles):
109
- * straightened by sight alone they would be drawn back to the corners they go round. Default 0: the furthest
110
- * point in sight.
111
- */
112
- lookClear: number;
113
75
  }
114
76
  export declare const DEFAULT_MARCH_RULES: Readonly<MarchRules>;
115
77
  /**
@@ -257,7 +219,7 @@ export interface March {
257
219
  blocked: boolean;
258
220
  /** The group is not marching in ranks for now (held by engagement, or most members acting on their own); it forms up again afterwards. */
259
221
  loose: boolean;
260
- /** Seconds the group still counts as opposed; while positive, members whose place is behind them walk on instead of waiting. */
222
+ /** Seconds the group still counts as opposed; while positive, members more than `pushAhead` ahead of their places may advance independently. */
261
223
  opposedT: number;
262
224
  /** Members with an opponent (counted every 8 steps). */
263
225
  cOpposed: number;
@@ -281,7 +243,7 @@ export interface March {
281
243
  /** The column's width and depth when not folded. */
282
244
  width: number;
283
245
  depth: number;
284
- /** The usable width recorded on each side where nothing was measured: half the width plus the largest member radius (with `MarchRules.flank`, the whole width plus that radius, so a rank has room to move over). */
246
+ /** The usable width recorded on each side where nothing was measured: the whole width plus the largest member radius, so a rank has room to move over. */
285
247
  open: number;
286
248
  /** Distance from the probe to the nearest narrow place on the trail (Infinity = none). */
287
249
  narrowB: number;
@@ -1,12 +1,12 @@
1
1
  export const DEFAULT_MARCH_RULES = Object.freeze({
2
2
  scale: 1,
3
- lagFull: 30, lagStop: 110, lagCap: 400, waitAhead: 14, turn: 1.4, turnR: 40, slide: 0.6, lookK: 0.75, lookMin: 96, probePad: 48,
3
+ lagFull: 30, lagStop: 110, lagCap: 400, pushAhead: Infinity, turn: 1.4, turnR: 40, slide: 0.6, lookK: 0.75, lookMin: 320, probePad: 48,
4
4
  holdEngaged: 0.15, trailStep: 12, overMin: 0.03, narrowIn: 0.55, narrowOut: 1, chokePad: 1, chokeMin: 32, narrow: 0.95,
5
- stretchMax: 4, axisFrom: 0.75, axisFull: 0.5, foldEase: 0.3, trot: 0.88, apartTrail: 0.3, rerouteCos: 0, tailMax: 20,
6
- opposedLinger: 5, leadTime: 0.4, flank: false, faceRoute: false, wheel: false, lookClear: 0,
5
+ stretchMax: 4, axisFrom: 0.5, axisFull: 0.3, foldEase: 0.3, trot: 0.88, rerouteCos: 0, tailMax: 20,
6
+ opposedLinger: 5, leadTime: 0.4,
7
7
  });
8
8
  /** The rules that are distances: the ones `marchRules` scales. */
9
- const LENGTHS = ['lagFull', 'lagStop', 'lagCap', 'waitAhead', 'turnR', 'lookMin', 'probePad', 'trailStep', 'chokePad', 'chokeMin'];
9
+ const LENGTHS = ['lagFull', 'lagStop', 'lagCap', 'pushAhead', 'turnR', 'lookMin', 'probePad', 'trailStep', 'chokePad', 'chokeMin'];
10
10
  /**
11
11
  * The default rules for a world `scale` times the size of the one they were made for (cells of about 32 units,
12
12
  * members about 12 across): every rule that is a distance is multiplied by `scale`, and so are the built-in
@@ -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.3.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": {