@anandommi/fields2cover 0.0.0-stage → 0.1.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/CHANGELOG.md +11 -0
- package/LICENSE +28 -0
- package/README.md +69 -2
- package/index.d.ts +58 -0
- package/index.js +13 -0
- package/lib/coverage.js +638 -0
- package/lib/decomposition.js +41 -0
- package/lib/frame.js +29 -0
- package/lib/geometry.js +269 -0
- package/lib/headland.js +51 -0
- package/lib/headlandLaps.js +520 -0
- package/lib/mowerLoopFallback.js +389 -0
- package/lib/mowerLoopPath.js +178 -0
- package/lib/mowerPath.js +219 -0
- package/lib/pathPlanner.js +362 -0
- package/lib/routeOrder.js +56 -0
- package/lib/swaths.js +46 -0
- package/package.json +45 -4
package/lib/coverage.js
ADDED
|
@@ -0,0 +1,638 @@
|
|
|
1
|
+
// Fields2Cover-style coverage planner, ported to JS (turf + local-metre
|
|
2
|
+
// geometry). Same pipeline and stage boundaries as F2C v2:
|
|
3
|
+
//
|
|
4
|
+
// hg headland.js constant-width headland around boundary and obstacles
|
|
5
|
+
// decomp decomposition.js boustrophedon cells, so rows never straddle an obstacle
|
|
6
|
+
// sg swaths.js parallel swaths along the reference line, per column
|
|
7
|
+
// hg headlandLaps.js headland swaths: laps that mow the headland band itself
|
|
8
|
+
// rp routeOrder.js leapfrog row order inside each cell + greedy cell order
|
|
9
|
+
// pp pathPlanner.js min-radius, loop-free Dubins turns, transit around obstacles
|
|
10
|
+
//
|
|
11
|
+
// Differences from F2C: the swath angle comes from the user's reference line
|
|
12
|
+
// (no brute-force angle search), cells are ordered greedily by reachable
|
|
13
|
+
// connection length instead of OR-tools, and every turn/transit is validated
|
|
14
|
+
// against the real drive area — rows whose connection cannot fit are retried
|
|
15
|
+
// later from elsewhere and only reported as skipped if nothing reaches them.
|
|
16
|
+
|
|
17
|
+
const { createLocalFrame, createSwathFrame } = require('./frame');
|
|
18
|
+
const { areaFromGeoJSON } = require('./geometry');
|
|
19
|
+
const { fieldArea, generateMainland } = require('./headland');
|
|
20
|
+
const { generateSwathColumns } = require('./swaths');
|
|
21
|
+
const { decomposeIntoCells } = require('./decomposition');
|
|
22
|
+
const { generateCustomOrder } = require('./routeOrder');
|
|
23
|
+
const { PathPlanner, pose, smoothWords } = require('./pathPlanner');
|
|
24
|
+
const { generateHeadlandLaps } = require('./headlandLaps');
|
|
25
|
+
|
|
26
|
+
const CONNECTOR_BOUNDARY_CLEARANCE_M = 0.3; // just enough to not sit exactly on the true boundary
|
|
27
|
+
const CONNECTOR_OBSTACLE_CLEARANCE_M = 1.0; // minimum physical safety gap from an obstacle during a turn
|
|
28
|
+
// Rows shorter than one turning radius (slivers where an obstacle's headland
|
|
29
|
+
// nearly meets the boundary's) each cost a full turn for almost no coverage.
|
|
30
|
+
const MIN_SWATH_LENGTH_M = 1;
|
|
31
|
+
const ROW_LOOKAHEAD = 4; // rows further along the order tried when the next one's turn does not fit
|
|
32
|
+
// A row end also counts as escapable when one turn gets 2-3 turning radii
|
|
33
|
+
// out: in a mainland narrower than a U-turn, a middle row ends with only the
|
|
34
|
+
// headland ahead (no single turn gets 4R away), yet the vehicle can still
|
|
35
|
+
// turn onto a headland lap and leave. Laps keep the stricter default.
|
|
36
|
+
const ROW_EXIT_ESCAPE_RADII = [2, 3, 4, 5];
|
|
37
|
+
const CELL_DIRECT_CANDIDATES = 12; // best-ranked cell entries tried with a single Dubins turn
|
|
38
|
+
const CELL_TRANSIT_CANDIDATES = 4; // nearest cell entries compared when a transit is needed
|
|
39
|
+
const LAP_CLEARANCE_MARGIN_M = 0.1; // keeps the outermost laps off the drive area's own edge
|
|
40
|
+
const LAP_ENTRY_STEP_M = 3; // spacing of candidate entry points along a lap
|
|
41
|
+
const LAP_ENTRY_MAX_CURVATURE_FACTOR = 0.8; // laps are entered only where they bend gentler than this × 1/R
|
|
42
|
+
const LAP_ENTRY_CLEARANCE_M = 3; // ...for at least this far either side of the entry point
|
|
43
|
+
const LAP_ENTRY_DENSIFY_M = 1;
|
|
44
|
+
const LAP_DIRECT_CANDIDATES = 40;
|
|
45
|
+
const LAP_TRANSIT_CANDIDATES = 4;
|
|
46
|
+
const MAX_LAP_BACKTRACKS = 60; // undo budget when the lap router paints itself into a corner
|
|
47
|
+
const NEXT_RING_DIRECT_CANDIDATES = 12; // entries on the neighbouring ring tried first, with a single turn
|
|
48
|
+
// ...only within this × R: a lane change onto the next ring, not a hop across
|
|
49
|
+
// the field that leaves the vehicle in a pocket between obstacles.
|
|
50
|
+
const NEXT_RING_REACH_FACTOR = 1;
|
|
51
|
+
const MAX_LAP_TRANSIT_FAILURES = 3; // a lap entry transits failed to this often (from different places) is not tried again
|
|
52
|
+
const TRIM_STEP_M = 2; // how far an open lap end is pulled back per escape check
|
|
53
|
+
const RANKED_ENTRY_POOL = 400; // nearest entries (straight-line) re-ranked by smooth turn length
|
|
54
|
+
const VIA_LAP_ON_CANDIDATES = 12; // lap entries tried for hopping onto a lap in a via-lap transit
|
|
55
|
+
const VIA_LAP_REACH_M = 30; // targets tried from points along that lap within this distance
|
|
56
|
+
const VIA_LAP_MAX_TURN_RAD = Math.PI + 0.35; // same no-loop limit as the path planner's turns
|
|
57
|
+
const VIA_LAP_STRAIGHT_BREAK_M = 0.5; // a straight this long ends one continuous turn
|
|
58
|
+
|
|
59
|
+
const statusError = (message, status = 400) => Object.assign(new Error(message), { status });
|
|
60
|
+
const distance = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]);
|
|
61
|
+
|
|
62
|
+
// Longest continuous same-direction turn along a polyline: a hop's arc, the
|
|
63
|
+
// lap's own bend and the next hop's arc chained together must not add up to
|
|
64
|
+
// a loop.
|
|
65
|
+
function longestPolylineTurn(points) {
|
|
66
|
+
let longest = 0;
|
|
67
|
+
let run = 0;
|
|
68
|
+
let straight = 0;
|
|
69
|
+
for (let i = 1; i + 1 < points.length; i += 1) {
|
|
70
|
+
const a = points[i - 1];
|
|
71
|
+
const b = points[i];
|
|
72
|
+
const c = points[i + 1];
|
|
73
|
+
const length = distance(b, c);
|
|
74
|
+
if (length < 1e-6 || distance(a, b) < 1e-6) continue;
|
|
75
|
+
let turn = Math.atan2(c[1] - b[1], c[0] - b[0]) - Math.atan2(b[1] - a[1], b[0] - a[0]);
|
|
76
|
+
turn = Math.atan2(Math.sin(turn), Math.cos(turn));
|
|
77
|
+
if (Math.abs(turn) < 2e-3) {
|
|
78
|
+
straight += length;
|
|
79
|
+
if (straight >= VIA_LAP_STRAIGHT_BREAK_M) run = 0;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
straight = 0;
|
|
83
|
+
run = Math.sign(run) === Math.sign(turn) ? run + turn : turn;
|
|
84
|
+
longest = Math.max(longest, Math.abs(run));
|
|
85
|
+
}
|
|
86
|
+
return longest;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const rowStart = (row, dir) => (dir > 0 ? row.a : row.b);
|
|
90
|
+
const rowEnd = (row, dir) => (dir > 0 ? row.b : row.a);
|
|
91
|
+
const rowHeading = (row, dir) => (dir > 0 ? row.heading : row.heading + Math.PI);
|
|
92
|
+
const entryPose = (row, dir) => pose(...rowStart(row, dir), rowHeading(row, dir));
|
|
93
|
+
const exitPose = (row, dir) => pose(...rowEnd(row, dir), rowHeading(row, dir));
|
|
94
|
+
|
|
95
|
+
// Adds points every LAP_ENTRY_DENSIFY_M along segments longer than that.
|
|
96
|
+
function densifyPath(points, closed) {
|
|
97
|
+
const out = [];
|
|
98
|
+
const n = points.length;
|
|
99
|
+
for (let i = 0; i < n; i += 1) {
|
|
100
|
+
const a = points[i];
|
|
101
|
+
out.push(a);
|
|
102
|
+
if (!closed && i === n - 1) break;
|
|
103
|
+
const b = points[(i + 1) % n];
|
|
104
|
+
const count = Math.floor(distance(a, b) / LAP_ENTRY_DENSIFY_M);
|
|
105
|
+
for (let k = 1; k < count; k += 1) {
|
|
106
|
+
out.push([a[0] + ((b[0] - a[0]) * k) / count, a[1] + ((b[1] - a[1]) * k) / count]);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Orders candidate entries by the length of the shortest loop-free turn into
|
|
113
|
+
// them (ignoring obstacles — that is checked afterwards). Straight-line
|
|
114
|
+
// distance alone puts targets right beside the vehicle first, and those are
|
|
115
|
+
// exactly the ones only a loop can reach.
|
|
116
|
+
function rankBySmoothTurn(from, radius, entries) {
|
|
117
|
+
return entries
|
|
118
|
+
.map((entry) => ({ entry, d: Math.hypot(entry.target.x - from.x, entry.target.y - from.y) }))
|
|
119
|
+
.sort((a, b) => a.d - b.d)
|
|
120
|
+
.slice(0, RANKED_ENTRY_POOL)
|
|
121
|
+
.map(({ entry, d }) => {
|
|
122
|
+
const word = smoothWords(from, entry.target, radius)[0];
|
|
123
|
+
return { entry, cost: word ? word.length : Infinity, d };
|
|
124
|
+
})
|
|
125
|
+
.sort((a, b) => a.cost - b.cost || a.d - b.d)
|
|
126
|
+
.map(({ entry }) => entry);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function buildCells(mainland, direction, spacing, turningRadius, pass) {
|
|
130
|
+
const swathFrame = createSwathFrame(direction);
|
|
131
|
+
const columns = generateSwathColumns(mainland, swathFrame, spacing, Math.max(MIN_SWATH_LENGTH_M, turningRadius));
|
|
132
|
+
return decomposeIntoCells(columns).map(({ rows }) => ({
|
|
133
|
+
pass,
|
|
134
|
+
rows: rows.map(({ u, v0, v1 }) => ({
|
|
135
|
+
u,
|
|
136
|
+
v0,
|
|
137
|
+
a: swathFrame.fromUV([u, v0]),
|
|
138
|
+
b: swathFrame.fromUV([u, v1]),
|
|
139
|
+
heading: swathFrame.heading
|
|
140
|
+
})),
|
|
141
|
+
order: generateCustomOrder(rows.length, spacing, turningRadius)
|
|
142
|
+
}));
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
class CoverageRoute {
|
|
146
|
+
constructor(planner, roads = []) {
|
|
147
|
+
this.planner = planner;
|
|
148
|
+
this.points = [];
|
|
149
|
+
this.pose = null;
|
|
150
|
+
this.escapable = new Map(); // row -> { f, r }: exit pose can still turn away
|
|
151
|
+
this.roads = roads; // headland laps, also usable as smooth roads for transits
|
|
152
|
+
this.roadStops = null;
|
|
153
|
+
this.transitFailures = new Map(); // lap entry target -> failed transits to it
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Last-resort transit for targets in a cul-de-sac that a direct turn or
|
|
157
|
+
// the visibility-graph transit cannot reach at the right heading: hop onto
|
|
158
|
+
// a headland lap, follow it, and hop off onto the target. Laps are already
|
|
159
|
+
// smooth, drivable curves, entered and left only where they bend gently;
|
|
160
|
+
// the whole chain is still checked so hop, lap bend and hop never add up
|
|
161
|
+
// to a loop.
|
|
162
|
+
viaLaps(targets) {
|
|
163
|
+
if (!this.roads.length || !targets.length) return null;
|
|
164
|
+
if (!this.roadStops) {
|
|
165
|
+
this.roadStops = new Map(); // pts -> entries along that lap direction, by index
|
|
166
|
+
this.roads.flatMap((lap) => this.lapEntries(lap)).forEach((stop) => {
|
|
167
|
+
if (!this.roadStops.has(stop.pts)) this.roadStops.set(stop.pts, []);
|
|
168
|
+
this.roadStops.get(stop.pts).push(stop);
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
const allStops = [...this.roadStops.values()].flat();
|
|
172
|
+
const ons = rankBySmoothTurn(this.pose, this.planner.radius, allStops).slice(0, VIA_LAP_ON_CANDIDATES);
|
|
173
|
+
let best = null;
|
|
174
|
+
for (const on of ons) {
|
|
175
|
+
const hopOn = this.planner.direct(this.pose, on.target);
|
|
176
|
+
if (!hopOn) continue;
|
|
177
|
+
const { pts, lap } = on;
|
|
178
|
+
const n = pts.length;
|
|
179
|
+
const ahead = (k) => (lap.closed ? (k - on.index + n) % n : k - on.index);
|
|
180
|
+
const stops = this.roadStops.get(pts)
|
|
181
|
+
.filter((stop) => ahead(stop.index) > 0)
|
|
182
|
+
.sort((a, b) => ahead(a.index) - ahead(b.index));
|
|
183
|
+
let along = 0;
|
|
184
|
+
let k = on.index;
|
|
185
|
+
for (const stop of stops) {
|
|
186
|
+
while (k !== stop.index) {
|
|
187
|
+
const next = (k + 1) % n;
|
|
188
|
+
along += distance(pts[k], pts[next]);
|
|
189
|
+
k = next;
|
|
190
|
+
}
|
|
191
|
+
const sofar = hopOn.length + along;
|
|
192
|
+
if (best && sofar >= best.connection.length) break;
|
|
193
|
+
let found = false;
|
|
194
|
+
for (const entry of targets) {
|
|
195
|
+
if (distance([stop.target.x, stop.target.y], [entry.target.x, entry.target.y]) > VIA_LAP_REACH_M) continue;
|
|
196
|
+
const hopOff = this.planner.direct(stop.target, entry.target);
|
|
197
|
+
if (!hopOff || (best && sofar + hopOff.length >= best.connection.length)) continue;
|
|
198
|
+
const road = [];
|
|
199
|
+
for (let j = on.index; j !== stop.index; j = (j + 1) % n) road.push(pts[(j + 1) % n]);
|
|
200
|
+
const points = [...hopOn.points, ...road.slice(0, -1), ...hopOff.points];
|
|
201
|
+
if (longestPolylineTurn(points) > VIA_LAP_MAX_TURN_RAD) continue;
|
|
202
|
+
best = { ...entry, connection: { points, length: sofar + hopOff.length } };
|
|
203
|
+
found = true;
|
|
204
|
+
}
|
|
205
|
+
if (found) break;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return best;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// True when the vehicle can still drive away smoothly after mowing `row`
|
|
212
|
+
// in direction `dir`. A row ending in a pocket too tight to turn in leaves
|
|
213
|
+
// the route stuck there, and every row after it becomes unreachable.
|
|
214
|
+
exitEscapable(row, dir) {
|
|
215
|
+
const key = dir > 0 ? 'f' : 'r';
|
|
216
|
+
let known = this.escapable.get(row);
|
|
217
|
+
if (!known) this.escapable.set(row, (known = {}));
|
|
218
|
+
if (!(key in known)) known[key] = this.planner.canEscape(exitPose(row, dir), ROW_EXIT_ESCAPE_RADII);
|
|
219
|
+
return known[key];
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Tries `connect` on each candidate entry and keeps the shortest result
|
|
223
|
+
// (or the first one, when stopAtFirst).
|
|
224
|
+
pick(candidates, connect, stopAtFirst) {
|
|
225
|
+
let best = null;
|
|
226
|
+
for (const entry of candidates) {
|
|
227
|
+
const connection = connect(this.pose, entry.target);
|
|
228
|
+
if (connection && (!best || connection.length < best.connection.length)) {
|
|
229
|
+
best = { ...entry, connection };
|
|
230
|
+
if (stopAtFirst) break;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return best;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
driveRow(row, dir, connection) {
|
|
237
|
+
if (connection) this.points.push(...connection.points.slice(1));
|
|
238
|
+
else this.points.push(rowStart(row, dir));
|
|
239
|
+
this.points.push(rowEnd(row, dir));
|
|
240
|
+
this.pose = exitPose(row, dir);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// Cheapest valid connection into `row`, either direction (the U-turn
|
|
244
|
+
// direction wins on length whenever it fits). Within a cell no obstacle
|
|
245
|
+
// lies between rows, so the fallback is only the two-hop turnaround — the
|
|
246
|
+
// full obstacle transit is left to the cell-level router.
|
|
247
|
+
connectRow(row, allowTurnaround) {
|
|
248
|
+
const tryWith = (connect) => {
|
|
249
|
+
let best = null;
|
|
250
|
+
for (const dir of [1, -1]) {
|
|
251
|
+
if (!this.exitEscapable(row, dir)) continue;
|
|
252
|
+
const connection = connect(this.pose, entryPose(row, dir));
|
|
253
|
+
if (connection && (!best || connection.length < best.connection.length)) best = { dir, connection };
|
|
254
|
+
}
|
|
255
|
+
return best;
|
|
256
|
+
};
|
|
257
|
+
return tryWith((a, b) => this.planner.direct(a, b))
|
|
258
|
+
|| (allowTurnaround ? tryWith((a, b) => this.planner.twoHop(a, b)) : null);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Drives one cell along its leapfrog sequence. A row whose turn does not
|
|
262
|
+
// fit is passed over for the next few in order and retried afterwards;
|
|
263
|
+
// rows still unreachable from inside the cell are returned as orphans for
|
|
264
|
+
// the cell-level router to reach from somewhere else.
|
|
265
|
+
runCell(cell, entry) {
|
|
266
|
+
const pending = entry.sequence.map((i) => cell.rows[i]);
|
|
267
|
+
this.driveRow(pending.shift(), entry.dir, entry.connection);
|
|
268
|
+
const orphans = [];
|
|
269
|
+
while (pending.length) {
|
|
270
|
+
let taken = -1;
|
|
271
|
+
let best = null;
|
|
272
|
+
for (let i = 0; i < Math.min(ROW_LOOKAHEAD, pending.length); i += 1) {
|
|
273
|
+
best = this.connectRow(pending[i], false);
|
|
274
|
+
if (best) {
|
|
275
|
+
taken = i;
|
|
276
|
+
break;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
if (taken < 0) {
|
|
280
|
+
best = this.connectRow(pending[0], true);
|
|
281
|
+
if (best) taken = 0;
|
|
282
|
+
}
|
|
283
|
+
if (taken < 0) {
|
|
284
|
+
orphans.push(pending.shift());
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
const [row] = pending.splice(taken, 1);
|
|
288
|
+
this.driveRow(row, best.dir, best.connection);
|
|
289
|
+
}
|
|
290
|
+
return orphans;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Each cell can be entered from either end of its sweep, on either row
|
|
294
|
+
// direction. Picks the cheapest entry a single smooth turn reaches; falls
|
|
295
|
+
// back to transiting when none does.
|
|
296
|
+
chooseNextCell(pool) {
|
|
297
|
+
const here = [this.pose.x, this.pose.y];
|
|
298
|
+
const entries = pool.flatMap((cell) => [false, true].flatMap((mirrored) => {
|
|
299
|
+
const n = cell.rows.length;
|
|
300
|
+
const sequence = mirrored ? cell.order.map((i) => n - 1 - i) : cell.order;
|
|
301
|
+
const first = cell.rows[sequence[0]];
|
|
302
|
+
return [1, -1].filter((dir) => this.exitEscapable(first, dir))
|
|
303
|
+
.map((dir) => ({ cell, sequence, dir, target: entryPose(first, dir) }));
|
|
304
|
+
}));
|
|
305
|
+
const ranked = rankBySmoothTurn(this.pose, this.planner.radius, entries);
|
|
306
|
+
entries.sort((a, b) => distance(here, [a.target.x, a.target.y]) - distance(here, [b.target.x, b.target.y]));
|
|
307
|
+
return this.pick(ranked.slice(0, CELL_DIRECT_CANDIDATES), (a, b) => this.planner.direct(a, b), false)
|
|
308
|
+
|| this.pick(entries.slice(0, CELL_TRANSIT_CANDIDATES), (a, b) => this.planner.transit(a, b), false)
|
|
309
|
+
|| this.pick(entries.slice(CELL_TRANSIT_CANDIDATES), (a, b) => this.planner.transit(a, b), true)
|
|
310
|
+
|| this.viaLaps(entries);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// Covers every cell of one pass. Returns the number of rows that could
|
|
314
|
+
// not be reached at all.
|
|
315
|
+
// Covers every cell of one pass. Returns the number of rows that could
|
|
316
|
+
// not be reached at all.
|
|
317
|
+
coverPass(cells) {
|
|
318
|
+
const pool = cells.filter((cell) => cell.rows.length > 0);
|
|
319
|
+
if (pool.length === 0) return 0;
|
|
320
|
+
|
|
321
|
+
if (!this.pose) {
|
|
322
|
+
// Start in the biggest cell, on its leftmost row (relative to the
|
|
323
|
+
// reference direction), driving along the reference line. Starting in
|
|
324
|
+
// a small side cell cut off by obstacles can strand the whole route
|
|
325
|
+
// there; from the main cell, side cells are reached afterwards or at
|
|
326
|
+
// worst skipped on their own. If the first row ends in a pocket the
|
|
327
|
+
// vehicle cannot turn out of, take the next start (other cell end,
|
|
328
|
+
// other direction, next cell) whose first row can be left again.
|
|
329
|
+
const sorted = [...pool].sort((a, b) => b.rows.length - a.rows.length
|
|
330
|
+
|| a.rows[0].u - b.rows[0].u || a.rows[0].v0 - b.rows[0].v0);
|
|
331
|
+
const starts = sorted.flatMap((cell) => [false, true].flatMap((mirrored) => [1, -1].map((dir) => {
|
|
332
|
+
const n = cell.rows.length;
|
|
333
|
+
return { cell, dir, sequence: mirrored ? cell.order.map((i) => n - 1 - i) : cell.order };
|
|
334
|
+
})));
|
|
335
|
+
const start = starts.find(({ cell, sequence, dir }) => this.exitEscapable(cell.rows[sequence[0]], dir)) || starts[0];
|
|
336
|
+
pool.splice(pool.indexOf(start.cell), 1);
|
|
337
|
+
this.runCell(start.cell, { sequence: start.sequence, dir: start.dir, connection: null })
|
|
338
|
+
.forEach((row) => pool.push({ pass: start.cell.pass, rows: [row], order: [0] }));
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
while (pool.length) {
|
|
342
|
+
const next = this.chooseNextCell(pool);
|
|
343
|
+
if (!next) {
|
|
344
|
+
// Nothing left is reachable from here, so nothing left ever will be.
|
|
345
|
+
return pool.reduce((sum, cell) => sum + cell.rows.length, 0);
|
|
346
|
+
}
|
|
347
|
+
pool.splice(pool.indexOf(next.cell), 1);
|
|
348
|
+
this.runCell(next.cell, next)
|
|
349
|
+
.forEach((row) => pool.push({ pass: next.cell.pass, rows: [row], order: [0] }));
|
|
350
|
+
}
|
|
351
|
+
return 0;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// Entry options along a lap (sampled), in both driving directions. A
|
|
355
|
+
// closed lap is driven fully round from its entry; an open piece from its
|
|
356
|
+
// entry to its end — the part behind the entry goes back in the pool.
|
|
357
|
+
lapEntries(lap) {
|
|
358
|
+
const out = [];
|
|
359
|
+
[false, true].forEach((reversed) => {
|
|
360
|
+
// Densified copy, so long straight sides (stored as just their two end
|
|
361
|
+
// points) get candidate entry points along them.
|
|
362
|
+
const pts = densifyPath(reversed ? [...lap.points].reverse() : lap.points, lap.closed);
|
|
363
|
+
const n = pts.length;
|
|
364
|
+
const headingAt = (k) => {
|
|
365
|
+
const a = pts[k];
|
|
366
|
+
const b = lap.closed ? pts[(k + 1) % n] : pts[Math.min(k + 1, n - 1)];
|
|
367
|
+
return Math.atan2(b[1] - a[1], b[0] - a[0]);
|
|
368
|
+
};
|
|
369
|
+
// Only where the lap bends gently over LAP_ENTRY_CLEARANCE_M either
|
|
370
|
+
// side (straights, wide orbits round an obstacle): entering — and, for
|
|
371
|
+
// a closed lap, leaving — at a tight corner manoeuvre would chain that
|
|
372
|
+
// arc with the connecting turn into a semicircle. Averaged over the
|
|
373
|
+
// window, so a wide orbit built from short straights and corner arcs
|
|
374
|
+
// still counts as the wide curve it is.
|
|
375
|
+
const pointAlong = (k, step) => {
|
|
376
|
+
let along = 0;
|
|
377
|
+
let j = k;
|
|
378
|
+
while (along < LAP_ENTRY_CLEARANCE_M) {
|
|
379
|
+
const next = j + step;
|
|
380
|
+
if (!lap.closed && (next < 0 || next >= n)) return null;
|
|
381
|
+
along += distance(pts[(j + n) % n], pts[(next + n) % n]);
|
|
382
|
+
j = next;
|
|
383
|
+
if (Math.abs(j - k) >= n) return null;
|
|
384
|
+
}
|
|
385
|
+
return { index: (j + n) % n, along };
|
|
386
|
+
};
|
|
387
|
+
const clearAround = (k) => {
|
|
388
|
+
if (!lap.closed && (k === 0 || k === n - 1)) return true;
|
|
389
|
+
const back = pointAlong(k, -1);
|
|
390
|
+
const ahead = pointAlong(k, 1);
|
|
391
|
+
if (!back || !ahead) return !lap.closed;
|
|
392
|
+
const hBack = Math.atan2(pts[(back.index + 1) % n][1] - pts[back.index][1], pts[(back.index + 1) % n][0] - pts[back.index][0]);
|
|
393
|
+
const hAhead = Math.atan2(pts[ahead.index][1] - pts[(ahead.index - 1 + n) % n][1], pts[ahead.index][0] - pts[(ahead.index - 1 + n) % n][0]);
|
|
394
|
+
let turn = hAhead - hBack;
|
|
395
|
+
turn = Math.abs(Math.atan2(Math.sin(turn), Math.cos(turn)));
|
|
396
|
+
return turn / (back.along + ahead.along) < LAP_ENTRY_MAX_CURVATURE_FACTOR / this.planner.radius;
|
|
397
|
+
};
|
|
398
|
+
let travelled = Infinity;
|
|
399
|
+
for (let k = 0; k < (lap.closed ? n : n - 1); k += 1) {
|
|
400
|
+
if (k > 0) travelled += distance(pts[k - 1], pts[k]);
|
|
401
|
+
if (travelled >= LAP_ENTRY_STEP_M && clearAround(k)) {
|
|
402
|
+
out.push({ lap, pts, index: k, target: pose(pts[k][0], pts[k][1], headingAt(k)) });
|
|
403
|
+
travelled = 0;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
});
|
|
407
|
+
return out;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// Drives a lap from the chosen entry. For an open piece entered part way
|
|
411
|
+
// along, returns the part behind the entry as a new open piece (or null).
|
|
412
|
+
driveLap({ lap, pts, index, connection }) {
|
|
413
|
+
const sequence = lap.closed ? [...pts.slice(index), ...pts.slice(0, index + 1)] : pts.slice(index);
|
|
414
|
+
const behind = lap.closed ? [] : pts.slice(0, index + 1);
|
|
415
|
+
if (connection) this.points.push(...connection.points.slice(1));
|
|
416
|
+
else this.points.push(sequence[0]);
|
|
417
|
+
this.points.push(...sequence.slice(1));
|
|
418
|
+
const a = sequence[sequence.length - 2];
|
|
419
|
+
const b = sequence[sequence.length - 1];
|
|
420
|
+
this.pose = pose(b[0], b[1], Math.atan2(b[1] - a[1], b[0] - a[0]));
|
|
421
|
+
const behindLength = behind.reduce((sum, p, i) => (i ? sum + distance(behind[i - 1], p) : 0), 0);
|
|
422
|
+
return behindLength >= this.planner.radius ? { closed: false, points: behind, depth: lap.depth } : null;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// Shortens an open piece from its end until the vehicle can still drive
|
|
426
|
+
// away smoothly from there; null when nothing of it is escapable.
|
|
427
|
+
trimToEscapableEnd(points) {
|
|
428
|
+
const pts = points.slice();
|
|
429
|
+
while (pts.length >= 2) {
|
|
430
|
+
const a = pts[pts.length - 2];
|
|
431
|
+
const b = pts[pts.length - 1];
|
|
432
|
+
if (this.planner.canEscape(pose(b[0], b[1], Math.atan2(b[1] - a[1], b[0] - a[0])))) return pts;
|
|
433
|
+
let removed = 0;
|
|
434
|
+
while (pts.length >= 2 && removed < TRIM_STEP_M) {
|
|
435
|
+
removed += distance(pts[pts.length - 2], pts[pts.length - 1]);
|
|
436
|
+
pts.pop();
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
return null;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// Open pieces end where a ring got too tight to follow — often a pocket
|
|
443
|
+
// the vehicle could drive into but not out of. Trim both ends back to
|
|
444
|
+
// where it can still leave smoothly.
|
|
445
|
+
escapablePiece(lap) {
|
|
446
|
+
if (lap.closed) return lap;
|
|
447
|
+
const forward = this.trimToEscapableEnd(lap.points);
|
|
448
|
+
const both = forward && this.trimToEscapableEnd([...forward].reverse());
|
|
449
|
+
if (!both) return null;
|
|
450
|
+
const length = both.reduce((sum, p, i) => (i ? sum + distance(both[i - 1], p) : 0), 0);
|
|
451
|
+
return length >= this.planner.radius ? { closed: false, points: both.reverse(), depth: lap.depth } : null;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// Mows the headland laps after the rows. From the end of each lap the
|
|
455
|
+
// cheapest reachable entry is usually the neighbouring lap one coverage
|
|
456
|
+
// width away, reached with a short lane-change S-curve. Returns the number
|
|
457
|
+
// of laps (or lap pieces) that could not be reached.
|
|
458
|
+
coverLaps(laps) {
|
|
459
|
+
const pool = laps.map((lap) => this.escapablePiece(lap)).filter(Boolean);
|
|
460
|
+
const dropped = laps.length - pool.length;
|
|
461
|
+
if (pool.length === 0) return dropped;
|
|
462
|
+
if (!this.pose) {
|
|
463
|
+
const first = pool.shift();
|
|
464
|
+
const remainder = this.driveLap({ lap: first, pts: first.points, index: 0, connection: null });
|
|
465
|
+
if (remainder) pool.push(remainder);
|
|
466
|
+
this.lapDepth = first.depth;
|
|
467
|
+
}
|
|
468
|
+
const entriesOf = new Map(pool.map((lap) => [lap, this.lapEntries(lap)]));
|
|
469
|
+
|
|
470
|
+
// Greedy, with bounded backtracking: when nothing left is reachable from
|
|
471
|
+
// where the last lap ended (a corridor too narrow to turn in, say), undo
|
|
472
|
+
// the last choices and try a different lap or entry instead of giving up
|
|
473
|
+
// on everything still in the pool.
|
|
474
|
+
const ids = new WeakMap(); // WeakMap has no size, so ids come from a counter
|
|
475
|
+
let nextId = 1;
|
|
476
|
+
const idOf = (obj) => {
|
|
477
|
+
if (!ids.has(obj)) ids.set(obj, nextId++);
|
|
478
|
+
return ids.get(obj);
|
|
479
|
+
};
|
|
480
|
+
const history = [];
|
|
481
|
+
const banned = new Set();
|
|
482
|
+
const stateKey = () => history.map((step) => step.key).join('>');
|
|
483
|
+
const entryKey = (entry) => `${idOf(entry.pts)}:${entry.index}`;
|
|
484
|
+
let backtracks = 0;
|
|
485
|
+
|
|
486
|
+
while (pool.length) {
|
|
487
|
+
const prefix = stateKey();
|
|
488
|
+
const allowed = (entry) => !banned.has(`${prefix}|${entryKey(entry)}`);
|
|
489
|
+
const next = this.chooseNextLap(pool, entriesOf, allowed);
|
|
490
|
+
if (!next) {
|
|
491
|
+
if (!history.length || backtracks >= MAX_LAP_BACKTRACKS) return dropped + pool.length;
|
|
492
|
+
backtracks += 1;
|
|
493
|
+
const step = history.pop();
|
|
494
|
+
this.points.length = step.pointsLength;
|
|
495
|
+
this.pose = step.pose;
|
|
496
|
+
this.lapDepth = step.depth;
|
|
497
|
+
if (step.remainder) {
|
|
498
|
+
pool.splice(pool.indexOf(step.remainder), 1);
|
|
499
|
+
entriesOf.delete(step.remainder);
|
|
500
|
+
}
|
|
501
|
+
pool.push(step.lap);
|
|
502
|
+
banned.add(`${stateKey()}|${step.key}`);
|
|
503
|
+
continue;
|
|
504
|
+
}
|
|
505
|
+
const step = { key: entryKey(next), lap: next.lap, pointsLength: this.points.length, pose: this.pose, depth: this.lapDepth, remainder: null };
|
|
506
|
+
pool.splice(pool.indexOf(next.lap), 1);
|
|
507
|
+
const remainder = this.driveLap(next);
|
|
508
|
+
if (remainder) {
|
|
509
|
+
pool.push(remainder);
|
|
510
|
+
entriesOf.set(remainder, this.lapEntries(remainder));
|
|
511
|
+
step.remainder = remainder;
|
|
512
|
+
}
|
|
513
|
+
this.lapDepth = next.lap.depth;
|
|
514
|
+
history.push(step);
|
|
515
|
+
}
|
|
516
|
+
return dropped;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// Best reachable lap entry from the current pose, among `allowed` ones.
|
|
520
|
+
// The ring nearest in depth to the one just mowed comes first (the deeper
|
|
521
|
+
// one on a tie, and the innermost ring, bordering the rows, when starting),
|
|
522
|
+
// so the laps are mowed ring by ring, each hop a short lane change of one
|
|
523
|
+
// coverage width, instead of hopping across rings the nearest turn happens
|
|
524
|
+
// to reach. Otherwise the cheapest smooth turn first, then transits.
|
|
525
|
+
chooseNextLap(pool, entriesOf, allowed) {
|
|
526
|
+
const depths = [...new Set(pool.map((lap) => lap.depth))];
|
|
527
|
+
const from = this.lapDepth == null ? Infinity : this.lapDepth;
|
|
528
|
+
const nextDepth = depths.reduce((best, d) => {
|
|
529
|
+
const gap = Math.abs(d - from);
|
|
530
|
+
const bestGap = Math.abs(best - from);
|
|
531
|
+
return gap < bestGap || (gap === bestGap && d > best) ? d : best;
|
|
532
|
+
});
|
|
533
|
+
const reach = NEXT_RING_REACH_FACTOR * this.planner.radius;
|
|
534
|
+
const nextRing = pool.filter((lap) => lap.depth === nextDepth).flatMap((lap) => entriesOf.get(lap)).filter(allowed)
|
|
535
|
+
.filter((entry) => Math.hypot(entry.target.x - this.pose.x, entry.target.y - this.pose.y) <= reach);
|
|
536
|
+
const onNextRing = this.pick(
|
|
537
|
+
rankBySmoothTurn(this.pose, this.planner.radius, nextRing).slice(0, NEXT_RING_DIRECT_CANDIDATES),
|
|
538
|
+
(a, b) => this.planner.direct(a, b),
|
|
539
|
+
false
|
|
540
|
+
);
|
|
541
|
+
if (onNextRing) return onNextRing;
|
|
542
|
+
|
|
543
|
+
const { x, y } = this.pose;
|
|
544
|
+
const entries = pool
|
|
545
|
+
.flatMap((lap) => entriesOf.get(lap))
|
|
546
|
+
.filter(allowed)
|
|
547
|
+
.map((entry) => ({ entry, d: Math.hypot(entry.target.x - x, entry.target.y - y) }))
|
|
548
|
+
.sort((a, b) => a.d - b.d)
|
|
549
|
+
.map(({ entry }) => entry);
|
|
550
|
+
const ranked = rankBySmoothTurn(this.pose, this.planner.radius, entries);
|
|
551
|
+
// Transit fallback over the rest tries just one (nearest) entry per lap.
|
|
552
|
+
const seen = new Set();
|
|
553
|
+
const onePerLap = entries.slice(LAP_TRANSIT_CANDIDATES).filter((e) => !seen.has(e.lap) && seen.add(e.lap));
|
|
554
|
+
return this.pick(ranked.slice(0, LAP_DIRECT_CANDIDATES), (a, b) => this.planner.direct(a, b), false)
|
|
555
|
+
|| this.pick(entries.slice(0, LAP_TRANSIT_CANDIDATES).filter((e) => this.transitWorthTrying(e)), (a, b) => this.lapTransit(a, b), false)
|
|
556
|
+
|| this.pick(onePerLap.filter((e) => this.transitWorthTrying(e)), (a, b) => this.lapTransit(a, b), true)
|
|
557
|
+
|| this.viaLaps(entries);
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// Lap entries no transit reaches (a ring round a small obstacle in a
|
|
561
|
+
// pocket, say) would otherwise be retried from every new position, each a
|
|
562
|
+
// full visibility-graph search that fails — most of the planning time with
|
|
563
|
+
// many obstacles. After a few failures from different places, give up on
|
|
564
|
+
// them; they stay reachable by direct turns and via other laps.
|
|
565
|
+
transitWorthTrying(entry) {
|
|
566
|
+
return (this.transitFailures.get(entry.target) || 0) < MAX_LAP_TRANSIT_FAILURES;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
lapTransit(from, target) {
|
|
570
|
+
const connection = this.planner.transit(from, target);
|
|
571
|
+
if (!connection) this.transitFailures.set(target, (this.transitFailures.get(target) || 0) + 1);
|
|
572
|
+
return connection;
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
function planCoverage({ polygonCoords, obstacleRings, referenceLineCoords, headlandWidth, spacing, turningRadius, crissCross }) {
|
|
577
|
+
if (!Number.isFinite(turningRadius) || turningRadius <= 0) {
|
|
578
|
+
throw statusError("A positive turning radius is required to generate the mower path.");
|
|
579
|
+
}
|
|
580
|
+
if (!Number.isFinite(spacing) || spacing <= 0) {
|
|
581
|
+
throw statusError("Spacing must be a positive number of metres.");
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
const frame = createLocalFrame(referenceLineCoords[0]);
|
|
585
|
+
const refStart = frame.toLocal(referenceLineCoords[0]);
|
|
586
|
+
const refEnd = frame.toLocal(referenceLineCoords[referenceLineCoords.length - 1]);
|
|
587
|
+
const refLength = distance(refStart, refEnd);
|
|
588
|
+
if (!(refLength > 1e-6)) throw statusError("The reference line needs two distinct end points.");
|
|
589
|
+
const direction = [(refEnd[0] - refStart[0]) / refLength, (refEnd[1] - refStart[1]) / refLength];
|
|
590
|
+
|
|
591
|
+
const mainlandFeature = generateMainland(polygonCoords, obstacleRings, headlandWidth);
|
|
592
|
+
const driveFeature = fieldArea(
|
|
593
|
+
polygonCoords,
|
|
594
|
+
obstacleRings,
|
|
595
|
+
Math.min(headlandWidth, CONNECTOR_BOUNDARY_CLEARANCE_M),
|
|
596
|
+
Math.min(headlandWidth, CONNECTOR_OBSTACLE_CLEARANCE_M)
|
|
597
|
+
);
|
|
598
|
+
const mainland = areaFromGeoJSON(mainlandFeature, frame.toLocal);
|
|
599
|
+
const driveArea = areaFromGeoJSON(driveFeature, frame.toLocal);
|
|
600
|
+
const planner = new PathPlanner({ driveArea, driveFeature, toLocal: frame.toLocal, radius: turningRadius });
|
|
601
|
+
|
|
602
|
+
// Criss-cross: the full primary grid first, then a second grid at 90°.
|
|
603
|
+
const directions = crissCross ? [direction, [direction[1], -direction[0]]] : [direction];
|
|
604
|
+
const passes = directions.map((dir, pass) => buildCells(mainland, dir, spacing, turningRadius, pass));
|
|
605
|
+
|
|
606
|
+
// Headland laps fill the band the rows leave for turning, so everything
|
|
607
|
+
// but the obstacles (and their clearance) is mowed.
|
|
608
|
+
const laps = generateHeadlandLaps({
|
|
609
|
+
polygonCoords,
|
|
610
|
+
obstacleRings,
|
|
611
|
+
headlandWidth,
|
|
612
|
+
spacing,
|
|
613
|
+
boundaryStart: Math.max(spacing / 2, CONNECTOR_BOUNDARY_CLEARANCE_M + LAP_CLEARANCE_MARGIN_M),
|
|
614
|
+
obstacleStart: Math.max(spacing / 2, CONNECTOR_OBSTACLE_CLEARANCE_M + LAP_CLEARANCE_MARGIN_M),
|
|
615
|
+
toLocal: frame.toLocal,
|
|
616
|
+
turningRadius,
|
|
617
|
+
driveArea
|
|
618
|
+
});
|
|
619
|
+
|
|
620
|
+
const route = new CoverageRoute(planner, laps);
|
|
621
|
+
let skipped = 0;
|
|
622
|
+
passes.forEach((cells) => {
|
|
623
|
+
skipped += route.coverPass(cells);
|
|
624
|
+
});
|
|
625
|
+
const skippedLaps = route.coverLaps(laps);
|
|
626
|
+
|
|
627
|
+
return {
|
|
628
|
+
coordinates: route.points.map(frame.toLonLat),
|
|
629
|
+
driveFeature,
|
|
630
|
+
rowCounts: passes.map((cells) => cells.reduce((sum, cell) => sum + cell.rows.length, 0)),
|
|
631
|
+
cellCount: passes.reduce((sum, cells) => sum + cells.length, 0),
|
|
632
|
+
skippedRows: skipped,
|
|
633
|
+
lapCount: laps.length,
|
|
634
|
+
skippedLaps
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
module.exports = { planCoverage, CONNECTOR_BOUNDARY_CLEARANCE_M, CONNECTOR_OBSTACLE_CLEARANCE_M };
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Port of Fields2Cover's decomp::BoustrophedonDecomp, done at swath
|
|
2
|
+
// resolution: sweep across the swath columns and keep extending a cell while
|
|
3
|
+
// each swath piece overlaps exactly one piece in the previous column (and
|
|
4
|
+
// vice versa). Where an obstacle or concave notch splits a column (one piece
|
|
5
|
+
// overlapping two) or two pieces merge back, the cell closes and new ones
|
|
6
|
+
// start — the same split/merge events BCD cuts at, without having to
|
|
7
|
+
// compute critical points on the polygon itself.
|
|
8
|
+
//
|
|
9
|
+
// Every cell is then a run of adjacent swaths, one piece per column, so a
|
|
10
|
+
// row pattern inside it never has to cross an obstacle between rows.
|
|
11
|
+
|
|
12
|
+
const overlaps = ([a0, a1], [b0, b1]) => Math.min(a1, b1) - Math.max(a0, b0) > 0;
|
|
13
|
+
|
|
14
|
+
function decomposeIntoCells(columns) {
|
|
15
|
+
const cells = [];
|
|
16
|
+
let open = []; // { cell, interval } from the previous column
|
|
17
|
+
|
|
18
|
+
columns.forEach(({ u, intervals }) => {
|
|
19
|
+
const prevMatches = open.map((o) => intervals.filter((q) => overlaps(o.interval, q)).length);
|
|
20
|
+
const next = intervals.map((q) => {
|
|
21
|
+
const matches = [];
|
|
22
|
+
open.forEach((o, index) => {
|
|
23
|
+
if (overlaps(o.interval, q)) matches.push(index);
|
|
24
|
+
});
|
|
25
|
+
let cell;
|
|
26
|
+
if (matches.length === 1 && prevMatches[matches[0]] === 1) {
|
|
27
|
+
cell = open[matches[0]].cell;
|
|
28
|
+
} else {
|
|
29
|
+
cell = { rows: [] };
|
|
30
|
+
cells.push(cell);
|
|
31
|
+
}
|
|
32
|
+
cell.rows.push({ u, v0: q[0], v1: q[1] });
|
|
33
|
+
return { cell, interval: q };
|
|
34
|
+
});
|
|
35
|
+
open = next;
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
return cells;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
module.exports = { decomposeIntoCells };
|