@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,218 @@
1
+ const turf = require('@turf/turf');
2
+ const { closeMowerPath } = require('./mowerLoopPath');
3
+ const { closeMowerPathFallback } = require('./mowerLoopFallback');
4
+ const { planCoverage, CONNECTOR_BOUNDARY_CLEARANCE_M, CONNECTOR_OBSTACLE_CLEARANCE_M } = require('./coverage');
5
+ const { fieldArea } = require('./headland');
6
+ const { createLocalFrame } = require('./frame');
7
+ const { normalizeObstacleRings } = require('./obstacleRings');
8
+
9
+ // Request handling for the Fields2Cover-style planner (POST
10
+ // /api/generateF2cMowerPath). Same request body and response shape as the
11
+ // existing /api/generateMowerPath, which is left untouched — this is a
12
+ // separate generator alongside it.
13
+
14
+ // Keep the join connector's endpoint under 50 cm from the first mowing point,
15
+ // same as the existing generator.
16
+ const LOOP_GAP_M = 0.3;
17
+
18
+ // Turns, connections and laps are sampled every 0.1 m while planning, which
19
+ // left ~130k points (7 MB+) on a 2 ha field — mostly on straight stretches.
20
+ // The output keeps only the points needed to stay within this distance of
21
+ // the planned path: a straight is just its two end points, an R = 6 m arc
22
+ // keeps a point about every 0.5 m.
23
+ const OUTPUT_TOLERANCE_M = 0.005;
24
+
25
+ // Douglas–Peucker in local metres (iterative, so long paths cannot overflow
26
+ // the stack). First and last points are always kept.
27
+ function simplifyPath(coordinates, tolerance) {
28
+ if (coordinates.length < 3) return coordinates;
29
+ const frame = createLocalFrame(coordinates[0]);
30
+ const pts = coordinates.map(frame.toLocal);
31
+ const keep = new Uint8Array(pts.length);
32
+ keep[0] = 1;
33
+ keep[pts.length - 1] = 1;
34
+ const stack = [[0, pts.length - 1]];
35
+ while (stack.length) {
36
+ const [first, last] = stack.pop();
37
+ const [ax, ay] = pts[first];
38
+ const dx = pts[last][0] - ax;
39
+ const dy = pts[last][1] - ay;
40
+ const len = Math.hypot(dx, dy);
41
+ let worst = -1;
42
+ let worstDist = tolerance;
43
+ for (let i = first + 1; i < last; i += 1) {
44
+ const px = pts[i][0] - ax;
45
+ const py = pts[i][1] - ay;
46
+ // Distance to the segment (to the end point when they coincide, e.g.
47
+ // a closed lap that starts and ends at the same spot).
48
+ let dist;
49
+ if (len < 1e-9) {
50
+ dist = Math.hypot(px, py);
51
+ } else {
52
+ const t = Math.max(0, Math.min(1, (px * dx + py * dy) / (len * len)));
53
+ dist = Math.hypot(px - t * dx, py - t * dy);
54
+ }
55
+ if (dist > worstDist) {
56
+ worstDist = dist;
57
+ worst = i;
58
+ }
59
+ }
60
+ if (worst >= 0) {
61
+ keep[worst] = 1;
62
+ stack.push([first, worst], [worst, last]);
63
+ }
64
+ }
65
+ return coordinates.filter((_, i) => keep[i]);
66
+ }
67
+
68
+ // Join start and end, with the same template-then-fallback strategy and the
69
+ // same strict safety check as the existing generator's applyLoopClosure.
70
+ function applyLoopClosure(result, { joinStartAndEnd, turningRadius, safeArea }) {
71
+ if (!joinStartAndEnd) return result;
72
+
73
+ if (!Number.isFinite(turningRadius) || turningRadius <= 0) {
74
+ const error = new Error('A positive turning radius is required to close the mower path.');
75
+ error.status = 422;
76
+ throw error;
77
+ }
78
+
79
+ const pathFeature = result.features.find((feature) => feature.geometry?.type === 'LineString');
80
+ if (!pathFeature) throw new Error('Generated mower path has no LineString to close.');
81
+
82
+ const isSafe = (connector) => {
83
+ if (!safeArea || connector.length < 2) return false;
84
+ if (!connector.every((point) => turf.booleanPointInPolygon(turf.point(point), safeArea))) return false;
85
+ return turf.booleanWithin(turf.lineString(connector), safeArea);
86
+ };
87
+
88
+ let loop = null;
89
+ try {
90
+ const template = closeMowerPath(pathFeature.geometry.coordinates, { turningRadius, gap: LOOP_GAP_M });
91
+ if (isSafe(template.connector)) loop = template;
92
+ } catch (templateError) {
93
+ console.warn("Loop template unavailable, using fallback planner:", templateError.message);
94
+ }
95
+ if (!loop) {
96
+ loop = closeMowerPathFallback(pathFeature.geometry.coordinates, { turningRadius, gap: LOOP_GAP_M, safeArea });
97
+ if (loop && !isSafe(loop.connector)) loop = null;
98
+ }
99
+ if (!loop) {
100
+ const error = new Error(
101
+ "Unable to join the mower path: no route at the configured turning radius from the end point back to the start stays inside the boundary and clear of obstacles. Try a smaller turning radius or a larger boundary offset."
102
+ );
103
+ error.code = "LOOP_CONNECTOR_OUTSIDE_SAFE_AREA";
104
+ error.status = 422;
105
+ throw error;
106
+ }
107
+ const totalLength = turf.length(turf.lineString(loop.coordinates), { units: 'meters' });
108
+ pathFeature.geometry.coordinates = loop.coordinates;
109
+ pathFeature.properties = {
110
+ ...(pathFeature.properties || {}),
111
+ ...loop.properties,
112
+ total_length_meters: Math.round(totalLength * 100) / 100,
113
+ is_closed_loop: false
114
+ };
115
+ return result;
116
+ }
117
+
118
+ // Pure — no req/res. Returns { status, result, contentDisposition } on
119
+ // success or { status, error, message? } on failure.
120
+ function computeF2cMowerPath(body) {
121
+ try {
122
+ if (!body) {
123
+ return { status: 400, error: "Missing request body" };
124
+ }
125
+ const {
126
+ polygonCoords,
127
+ referenceLineCoords,
128
+ offsetDistance,
129
+ spacing,
130
+ turningRadius,
131
+ crissCross,
132
+ obstacleAvoid,
133
+ obstaclePolygons
134
+ } = body;
135
+
136
+ if (!polygonCoords || !referenceLineCoords || offsetDistance == null || offsetDistance === "" || !spacing) {
137
+ return { status: 400, error: "Missing required parameters" };
138
+ }
139
+ // The headland is where every turn happens, so it must be a real width.
140
+ const headlandWidth = Number(offsetDistance);
141
+ if (!Number.isFinite(headlandWidth) || headlandWidth <= 0) {
142
+ return { status: 400, error: "offsetDistance must be a number greater than 0." };
143
+ }
144
+ if (!Array.isArray(polygonCoords) || polygonCoords.length < 4) {
145
+ return { status: 400, error: "polygonCoords must be an array of at least 4 [lng, lat] positions." };
146
+ }
147
+ if (!Array.isArray(referenceLineCoords) || referenceLineCoords.length < 2) {
148
+ return { status: 400, error: "referenceLineCoords must be an array of at least 2 [lng, lat] positions." };
149
+ }
150
+
151
+ // Obstacles only shape the rows and turns when obstacle-avoid is on.
152
+ const obstacles = normalizeObstacleRings(obstaclePolygons);
153
+ const obstacleAware = !!obstacleAvoid && obstacles.length > 0;
154
+
155
+ const plan = planCoverage({
156
+ polygonCoords,
157
+ obstacleRings: obstacleAware ? obstacles : [],
158
+ referenceLineCoords,
159
+ headlandWidth,
160
+ spacing: Number(spacing),
161
+ turningRadius: Number(turningRadius),
162
+ crissCross: !!crissCross
163
+ });
164
+
165
+ if (plan.coordinates.length < 2) {
166
+ return { status: 400, error: "No swath lines could be generated. Offset/obstacles may be too large for this polygon." };
167
+ }
168
+
169
+ const totalLength = turf.length(turf.lineString(plan.coordinates), { units: "meters" });
170
+ const result = {
171
+ type: "FeatureCollection",
172
+ features: [
173
+ {
174
+ type: "Feature",
175
+ properties: {
176
+ type: "complete_mower_path",
177
+ total_length_meters: Math.round(totalLength * 100) / 100,
178
+ is_computer_generated: true,
179
+ planner: "fields2cover",
180
+ criss_cross: !!crissCross,
181
+ obstacle_aware: obstacleAware,
182
+ obstacle_count: obstacleAware ? obstacles.length : 0
183
+ },
184
+ geometry: { type: "LineString", coordinates: plan.coordinates }
185
+ }
186
+ ]
187
+ };
188
+
189
+ // The join connector must stay inside the boundary and clear of obstacles
190
+ // even when obstacle-avoid is off for the mowing rows themselves.
191
+ let loopSafeArea = plan.driveFeature;
192
+ if (body.joinStartAndEnd && !obstacleAware && obstacles.length) {
193
+ loopSafeArea = fieldArea(
194
+ polygonCoords,
195
+ obstacles,
196
+ Math.min(headlandWidth, CONNECTOR_BOUNDARY_CLEARANCE_M),
197
+ Math.min(headlandWidth, CONNECTOR_OBSTACLE_CLEARANCE_M)
198
+ );
199
+ }
200
+ applyLoopClosure(result, { joinStartAndEnd: !!body.joinStartAndEnd, turningRadius, safeArea: loopSafeArea });
201
+ const pathGeometry = result.features[0].geometry;
202
+ pathGeometry.coordinates = simplifyPath(pathGeometry.coordinates, OUTPUT_TOLERANCE_M);
203
+ return {
204
+ status: 200,
205
+ result,
206
+ contentDisposition: `attachment; filename=mower_path_f2c${crissCross ? "_grid" : ""}${obstacleAware ? "_obstacle_aware" : ""}.geojson`
207
+ };
208
+ } catch (error) {
209
+ console.error("Error generating F2C mower path:", error);
210
+ return {
211
+ status: error.status || 500,
212
+ error: error.status ? error.message : "Failed to generate mower path",
213
+ ...(error.status ? {} : { message: error.message })
214
+ };
215
+ }
216
+ }
217
+
218
+ module.exports = { computeF2cMowerPath };
@@ -0,0 +1,50 @@
1
+ const turf = require('@turf/turf');
2
+
3
+ // Obstacle outlines usually come from a recorded drive around the obstacle
4
+ // (mission file LineStrings closed into Polygons on upload). On a long, thin
5
+ // obstacle the return leg wanders across the outbound leg, so the ring
6
+ // self-intersects. turf.buffer on such an invalid polygon returns garbage: a
7
+ // ~136 m x 5 m strip buffered by 0.5 m came back as 11 m² instead of ~700 m²,
8
+ // so the connector/transit drive area ignored the obstacle and turns were
9
+ // routed straight through it.
10
+ //
11
+ // Normalise every ring into a valid simple polygon covering everything the
12
+ // outline encloses: buffer the outline as a line by a few centimetres (always
13
+ // valid, whatever the self-crossings), union the pieces and keep only the
14
+ // exterior ring(s) so any enclosed pocket is filled rather than left as a hole.
15
+ const OUTLINE_BUFFER_M = 0.05;
16
+
17
+ function closeRing(coords) {
18
+ const first = coords[0];
19
+ const last = coords[coords.length - 1];
20
+ return first[0] === last[0] && first[1] === last[1] ? coords : [...coords, first];
21
+ }
22
+
23
+ function exteriorRings(geometry) {
24
+ if (!geometry) return [];
25
+ if (geometry.type === 'Polygon') return [geometry.coordinates[0]];
26
+ if (geometry.type === 'MultiPolygon') return geometry.coordinates.map((poly) => poly[0]);
27
+ return [];
28
+ }
29
+
30
+ function normalizeObstacleRing(coords) {
31
+ if (!Array.isArray(coords) || coords.length < 3) return [];
32
+ const ring = closeRing(coords);
33
+ if (ring.length < 4) return [];
34
+ try {
35
+ const outline = turf.buffer(turf.lineString(ring), OUTLINE_BUFFER_M / 1000, { units: 'kilometers' });
36
+ const rings = exteriorRings(outline?.geometry).filter((r) => r.length >= 4);
37
+ if (rings.length > 0) return rings;
38
+ } catch (err) {
39
+ // fall through to the raw ring
40
+ }
41
+ return [ring];
42
+ }
43
+
44
+ // Array of [lng, lat] rings in -> array of valid, closed, hole-free rings out.
45
+ function normalizeObstacleRings(rings) {
46
+ if (!Array.isArray(rings)) return [];
47
+ return rings.flatMap(normalizeObstacleRing);
48
+ }
49
+
50
+ module.exports = { normalizeObstacleRings };