@anandommi/fields2cover 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 };
package/lib/frame.js ADDED
@@ -0,0 +1,29 @@
1
+ // Local east/north metre frame around an origin (equirectangular with WGS84
2
+ // metre-per-degree terms). Accurate to well under a centimetre across a
3
+ // field-sized area and cheap enough to run on every sampled path point, so
4
+ // all planning (swaths, decomposition, Dubins turns, safety checks) happens
5
+ // in metres instead of mixing degrees with a metre-based turning radius.
6
+ function createLocalFrame(origin) {
7
+ const lat0 = origin[1] * Math.PI / 180;
8
+ const metersPerDegLat = 111132.92 - 559.82 * Math.cos(2 * lat0) + 1.175 * Math.cos(4 * lat0);
9
+ const metersPerDegLon = 111412.84 * Math.cos(lat0) - 93.5 * Math.cos(3 * lat0);
10
+ return {
11
+ toLocal: ([lon, lat]) => [(lon - origin[0]) * metersPerDegLon, (lat - origin[1]) * metersPerDegLat],
12
+ toLonLat: ([x, y]) => [origin[0] + x / metersPerDegLon, origin[1] + y / metersPerDegLat]
13
+ };
14
+ }
15
+
16
+ // Swath frame (u, v): v runs along the swath direction, u across it (to the
17
+ // right of the direction). Swaths are then just vertical lines u = const.
18
+ function createSwathFrame(direction) {
19
+ const [dx, dy] = direction;
20
+ const nx = dy;
21
+ const ny = -dx;
22
+ return {
23
+ heading: Math.atan2(dy, dx),
24
+ toUV: ([x, y]) => [x * nx + y * ny, x * dx + y * dy],
25
+ fromUV: ([u, v]) => [u * nx + v * dx, u * ny + v * dy]
26
+ };
27
+ }
28
+
29
+ module.exports = { createLocalFrame, createSwathFrame };
@@ -0,0 +1,269 @@
1
+ // Planar geometry in the local metre frame (see frame.js). An "area" is a set
2
+ // of polygons-with-holes, [[outerRing, ...holeRings], ...], each ring an array
3
+ // of [x, y] (closed or not) — the shape GeoJSON Polygon/MultiPolygon already
4
+ // uses, just projected to metres.
5
+
6
+ const VISIBILITY_SAMPLE_STEP_M = 2;
7
+
8
+ function ringContains(ring, x, y) {
9
+ let inside = false;
10
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i, i += 1) {
11
+ const [xi, yi] = ring[i];
12
+ const [xj, yj] = ring[j];
13
+ if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;
14
+ }
15
+ return inside;
16
+ }
17
+
18
+ function ringBounds(ring) {
19
+ let minX = Infinity;
20
+ let minY = Infinity;
21
+ let maxX = -Infinity;
22
+ let maxY = -Infinity;
23
+ ring.forEach(([x, y]) => {
24
+ if (x < minX) minX = x;
25
+ if (y < minY) minY = y;
26
+ if (x > maxX) maxX = x;
27
+ if (y > maxY) maxY = y;
28
+ });
29
+ return { minX, minY, maxX, maxY };
30
+ }
31
+
32
+ const orient = (ax, ay, bx, by, cx, cy) => (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
33
+
34
+ // Uniform grid over the boundary edges, so containment and visibility checks
35
+ // look only at the edges near the query instead of every edge of the
36
+ // boundary and every obstacle — those checks are most of the planning time
37
+ // once there are obstacles.
38
+ const GRID_TARGET_CELLS = 250000;
39
+ const GRID_MIN_CELL_M = 1;
40
+ const GRID_EPS = 1e-6;
41
+ function createEdgeGrid(edges) {
42
+ if (edges.length < 64) return null; // a plain scan is as fast
43
+ let minX = Infinity;
44
+ let minY = Infinity;
45
+ let maxX = -Infinity;
46
+ let maxY = -Infinity;
47
+ edges.forEach((e) => {
48
+ minX = Math.min(minX, e.minX);
49
+ minY = Math.min(minY, e.minY);
50
+ maxX = Math.max(maxX, e.maxX);
51
+ maxY = Math.max(maxY, e.maxY);
52
+ });
53
+ const size = Math.max(GRID_MIN_CELL_M, Math.sqrt(((maxX - minX) * (maxY - minY)) / GRID_TARGET_CELLS));
54
+ const cols = Math.floor((maxX - minX) / size) + 1;
55
+ const rows = Math.floor((maxY - minY) / size) + 1;
56
+ const col = (x) => Math.floor((x - minX) / size);
57
+ const row = (y) => Math.floor((y - minY) / size);
58
+ const clampCol = (c) => Math.min(cols - 1, Math.max(0, c));
59
+ const clampRow = (r) => Math.min(rows - 1, Math.max(0, r));
60
+
61
+ const cells = new Array(cols * rows).fill(null);
62
+ edges.forEach((e, index) => {
63
+ const c0 = clampCol(col(e.minX - GRID_EPS));
64
+ const c1 = clampCol(col(e.maxX + GRID_EPS));
65
+ const r0 = clampRow(row(e.minY - GRID_EPS));
66
+ const r1 = clampRow(row(e.maxY + GRID_EPS));
67
+ for (let r = r0; r <= r1; r += 1) {
68
+ for (let c = c0; c <= c1; c += 1) {
69
+ const k = r * cols + c;
70
+ (cells[k] || (cells[k] = [])).push(index);
71
+ }
72
+ }
73
+ });
74
+
75
+ const stamps = new Int32Array(edges.length);
76
+ let stampCounter = 0;
77
+ const nextStamp = () => {
78
+ stampCounter += 1;
79
+ if (stampCounter === 2147483647) {
80
+ stamps.fill(0);
81
+ stampCounter = 1;
82
+ }
83
+ return stampCounter;
84
+ };
85
+ const uniform = new Int8Array(cols * rows); // 0 unknown, 1 inside, 2 outside
86
+ const uniformState = (k, containsSlow) => {
87
+ if (!uniform[k]) {
88
+ const c = k % cols;
89
+ const r = (k - c) / cols;
90
+ uniform[k] = containsSlow(minX + (c + 0.5) * size, minY + (r + 0.5) * size) ? 1 : 2;
91
+ }
92
+ return uniform[k] === 1;
93
+ };
94
+
95
+ // Edges in the cells the segment a→b passes through (each once), walking
96
+ // the grid along the segment; the segment's ends are clamped onto the grid,
97
+ // as nothing outside it has edges.
98
+ const edgesNear = (ax, ay, bx, by) => {
99
+ const out = [];
100
+ const stamp = nextStamp();
101
+ const visit = (c, r) => {
102
+ if (c < 0 || r < 0 || c >= cols || r >= rows) return;
103
+ const cell = cells[r * cols + c];
104
+ if (!cell) return;
105
+ for (const index of cell) {
106
+ if (stamps[index] === stamp) continue;
107
+ stamps[index] = stamp;
108
+ out.push(edges[index]);
109
+ }
110
+ };
111
+ let c = col(ax);
112
+ let r = row(ay);
113
+ const cEnd = col(bx);
114
+ const rEnd = row(by);
115
+ const dx = bx - ax;
116
+ const dy = by - ay;
117
+ const stepC = dx > 0 ? 1 : -1;
118
+ const stepR = dy > 0 ? 1 : -1;
119
+ const tDeltaC = dx !== 0 ? size / Math.abs(dx) : Infinity;
120
+ const tDeltaR = dy !== 0 ? size / Math.abs(dy) : Infinity;
121
+ let tMaxC = dx !== 0 ? ((minX + (c + (dx > 0 ? 1 : 0)) * size) - ax) / dx : Infinity;
122
+ let tMaxR = dy !== 0 ? ((minY + (r + (dy > 0 ? 1 : 0)) * size) - ay) / dy : Infinity;
123
+ const limit = Math.abs(cEnd - c) + Math.abs(rEnd - r) + 2;
124
+ for (let n = 0; n <= limit; n += 1) {
125
+ // Edges sit in every cell within GRID_EPS of them, so a walk rounded
126
+ // past a cell corner still meets any edge the segment crosses there.
127
+ visit(c, r);
128
+ if (c === cEnd && r === rEnd) break;
129
+ if (tMaxC < tMaxR) {
130
+ c += stepC;
131
+ tMaxC += tDeltaC;
132
+ } else {
133
+ r += stepR;
134
+ tMaxR += tDeltaR;
135
+ }
136
+ }
137
+ return out;
138
+ };
139
+
140
+ return { cols, rows, col, row, cells, stamps, nextStamp, uniformState, edgesNear };
141
+ }
142
+
143
+ function createArea(polygons) {
144
+ const parts = polygons
145
+ .filter((rings) => rings.length && rings[0].length >= 3)
146
+ .map((rings) => ({ rings, bounds: ringBounds(rings[0]), holes: rings.slice(1).map((ring) => ({ ring, bounds: ringBounds(ring) })) }));
147
+
148
+ const edges = [];
149
+ parts.forEach(({ rings }) => rings.forEach((ring) => {
150
+ for (let i = 0; i < ring.length; i += 1) {
151
+ const [ax, ay] = ring[i];
152
+ const [bx, by] = ring[(i + 1) % ring.length];
153
+ if (ax === bx && ay === by) continue;
154
+ edges.push({
155
+ ax, ay, bx, by,
156
+ minX: Math.min(ax, bx), maxX: Math.max(ax, bx),
157
+ minY: Math.min(ay, by), maxY: Math.max(ay, by)
158
+ });
159
+ }
160
+ }));
161
+
162
+ const inBounds = (b, x, y) => x >= b.minX && x <= b.maxX && y >= b.minY && y <= b.maxY;
163
+ const containsSlow = (x, y) => parts.some(({ rings, bounds, holes }) =>
164
+ inBounds(bounds, x, y) && ringContains(rings[0], x, y) &&
165
+ !holes.some((hole) => inBounds(hole.bounds, x, y) && ringContains(hole.ring, x, y)));
166
+
167
+ const grid = createEdgeGrid(edges);
168
+ // Same answer as containsSlow, from local edges only: a cell no edge
169
+ // touches is wholly inside or wholly outside, so a point is classified by
170
+ // counting the edge crossings of a ray to the next such cell along its row.
171
+ const contains = (x, y) => {
172
+ if (!grid) return containsSlow(x, y);
173
+ const cx = grid.col(x);
174
+ const cy = grid.row(y);
175
+ if (cx < 0 || cy < 0 || cx >= grid.cols || cy >= grid.rows) return containsSlow(x, y);
176
+ let inside = false;
177
+ const stamp = grid.nextStamp();
178
+ for (let c = cx; c < grid.cols; c += 1) {
179
+ const cell = grid.cells[cy * grid.cols + c];
180
+ if (!cell) {
181
+ if (c === cx) return grid.uniformState(cy * grid.cols + c, containsSlow);
182
+ return inside !== grid.uniformState(cy * grid.cols + c, containsSlow);
183
+ }
184
+ for (const index of cell) {
185
+ if (grid.stamps[index] === stamp) continue;
186
+ grid.stamps[index] = stamp;
187
+ const e = edges[index];
188
+ if ((e.ay > y) !== (e.by > y) && x < ((e.bx - e.ax) * (y - e.ay)) / (e.by - e.ay) + e.ax) inside = !inside;
189
+ }
190
+ }
191
+ return inside; // ray left the grid, and nothing lies beyond it
192
+ };
193
+
194
+ return {
195
+ polygons: parts.map(({ rings }) => rings),
196
+ edges,
197
+ contains,
198
+ containsAll: (points) => points.every(([x, y]) => contains(x, y)),
199
+ // True when the straight segment a→b stays inside the area: it properly
200
+ // crosses no boundary edge and its interior samples are all inside
201
+ // (catches the rare pass exactly through a vertex).
202
+ segmentClear([ax, ay], [bx, by]) {
203
+ const minX = Math.min(ax, bx);
204
+ const maxX = Math.max(ax, bx);
205
+ const minY = Math.min(ay, by);
206
+ const maxY = Math.max(ay, by);
207
+ for (const e of grid ? grid.edgesNear(ax, ay, bx, by) : edges) {
208
+ if (e.maxX < minX || e.minX > maxX || e.maxY < minY || e.minY > maxY) continue;
209
+ const o1 = orient(ax, ay, bx, by, e.ax, e.ay);
210
+ const o2 = orient(ax, ay, bx, by, e.bx, e.by);
211
+ const o3 = orient(e.ax, e.ay, e.bx, e.by, ax, ay);
212
+ const o4 = orient(e.ax, e.ay, e.bx, e.by, bx, by);
213
+ if (o1 * o2 < 0 && o3 * o4 < 0) return false;
214
+ }
215
+ const length = Math.hypot(bx - ax, by - ay);
216
+ const count = Math.max(2, Math.ceil(length / VISIBILITY_SAMPLE_STEP_M));
217
+ for (let i = 1; i < count; i += 1) {
218
+ const t = i / count;
219
+ if (!contains(ax + (bx - ax) * t, ay + (by - ay) * t)) return false;
220
+ }
221
+ return true;
222
+ }
223
+ };
224
+ }
225
+
226
+ // GeoJSON Polygon/MultiPolygon (Feature or geometry) → area in local metres.
227
+ function areaFromGeoJSON(feature, toLocal) {
228
+ const geometry = feature?.geometry || feature;
229
+ if (!geometry) return createArea([]);
230
+ const polygons = geometry.type === "Polygon" ? [geometry.coordinates]
231
+ : geometry.type === "MultiPolygon" ? geometry.coordinates : [];
232
+ return createArea(polygons.map((rings) => rings.map((ring) => ring.map(toLocal))));
233
+ }
234
+
235
+ function signedRingArea(ring) {
236
+ let sum = 0;
237
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i, i += 1) {
238
+ sum += (ring[j][0] - ring[i][0]) * (ring[j][1] + ring[i][1]);
239
+ }
240
+ return sum / 2;
241
+ }
242
+
243
+ const openRing = (ring) => {
244
+ const last = ring[ring.length - 1];
245
+ return ring.length > 1 && last[0] === ring[0][0] && last[1] === ring[0][1] ? ring.slice(0, -1) : ring;
246
+ };
247
+
248
+ // Vertices where the free space bends around a corner (its interior angle is
249
+ // over 180°): convex corners of obstacles and inward notches of the outer
250
+ // boundary. A shortest path inside a polygon only ever bends at these.
251
+ function freeSpaceReflexVertices(area) {
252
+ const out = [];
253
+ area.polygons.forEach((rings) => rings.forEach((rawRing, ringIndex) => {
254
+ let ring = openRing(rawRing);
255
+ if (ring.length < 3) return;
256
+ // Orient so free space is on the left: outer ring CCW, holes CW.
257
+ const ccw = signedRingArea(ring) > 0;
258
+ if ((ringIndex === 0) !== ccw) ring = [...ring].reverse();
259
+ for (let i = 0; i < ring.length; i += 1) {
260
+ const p = ring[(i - 1 + ring.length) % ring.length];
261
+ const v = ring[i];
262
+ const n = ring[(i + 1) % ring.length];
263
+ if (orient(p[0], p[1], v[0], v[1], n[0], n[1]) < 0) out.push(v);
264
+ }
265
+ }));
266
+ return out;
267
+ }
268
+
269
+ module.exports = { createArea, areaFromGeoJSON, freeSpaceReflexVertices };
@@ -0,0 +1,51 @@
1
+ const turf = require('@turf/turf');
2
+
3
+ // Port of Fields2Cover's hg::ConstHL (constant-width headland generator):
4
+ // the field is the boundary with obstacles as holes, and the "mainland" where
5
+ // swaths go is that field shrunk by the headland width on every side —
6
+ // including around every obstacle, so each obstacle gets its own turning
7
+ // ring. Polygon offsetting stays in lon/lat through turf.buffer (geodesic,
8
+ // handles holes and merging); everything downstream works in local metres.
9
+
10
+ // Boundaries/obstacles drawn from a dense recorded path (thousands of
11
+ // GPS-jitter-close points) make turf's buffer/clip math numerically
12
+ // unreliable. Simplifying to ~0.3 m first removes that noise without visibly
13
+ // changing the shape (well under 0.1% area change in practice).
14
+ const RING_SIMPLIFY_TOLERANCE_DEG = 0.000003; // ~0.3m
15
+ function simplifyRing(coords) {
16
+ if (!Array.isArray(coords) || coords.length <= 20) return coords;
17
+ const simplified = turf.simplify(turf.polygon([coords]), { tolerance: RING_SIMPLIFY_TOLERANCE_DEG, highQuality: true });
18
+ const simplifiedRing = simplified.geometry.coordinates[0];
19
+ return simplifiedRing.length >= 4 ? simplifiedRing : coords;
20
+ }
21
+
22
+ const bufferMeters = (feature, meters) => turf.buffer(feature, meters / 1000, { units: "kilometers" });
23
+
24
+ const statusError = (message, status = 400) => Object.assign(new Error(message), { status });
25
+
26
+ // Boundary shrunk by `boundaryInset` minus every obstacle grown by
27
+ // `obstacleGrow` (both metres). Returns a lon/lat Polygon/MultiPolygon.
28
+ function fieldArea(polygonCoords, obstacleRings, boundaryInset, obstacleGrow) {
29
+ const boundary = turf.polygon([simplifyRing(polygonCoords)]);
30
+ const area = boundaryInset > 0 ? bufferMeters(boundary, -boundaryInset) : boundary;
31
+ if (!area) throw statusError("Boundary offset leaves no driveable area");
32
+
33
+ const grown = (obstacleRings || [])
34
+ .filter((coords) => Array.isArray(coords) && coords.length >= 4)
35
+ .map((coords) => bufferMeters(turf.polygon([simplifyRing(coords)]), obstacleGrow))
36
+ .filter(Boolean);
37
+ if (grown.length === 0) return area;
38
+
39
+ const obstacleUnion = grown.length === 1 ? grown[0] : turf.union(turf.featureCollection(grown));
40
+ if (!obstacleUnion) return area;
41
+ const diff = turf.difference(turf.featureCollection([area, obstacleUnion]));
42
+ if (!diff) throw statusError("Obstacles fully cover the driveable area — nothing left to mow");
43
+ return diff;
44
+ }
45
+
46
+ // Mainland for swaths: the constant-width headland on every side.
47
+ function generateMainland(polygonCoords, obstacleRings, headlandWidth) {
48
+ return fieldArea(polygonCoords, obstacleRings, headlandWidth, headlandWidth);
49
+ }
50
+
51
+ module.exports = { fieldArea, generateMainland, bufferMeters, simplifyRing };