Skip to content

Follow connection polylines instead of cutting across them - #234

Merged
Gonzalo-Mier merged 11 commits into
Fields2Cover:mainfrom
u33549:dev/umutc/v2.1.0-devel/connection-tracking
Aug 22, 2026
Merged

Gonzalo-Mier merged 11 commits into
Fields2Cover:mainfrom
u33549:dev/umutc/v2.1.0-devel/connection-tracking

Conversation

@u33549

@u33549 u33549 commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

planPathForConnection() ignores the polyline it is given. It hands every consecutive pose
pair to the turn planner, so a connection detouring around a concave notch or between
decomposed cells is driven straight from one end to the other, cutting across ground the
route deliberately routed around. simplifyConnection() also compares headings with
fabs(ang_in - ang_out) on raw angles, which wraps wrong.

The library's own test says as much: planPathForConnection has been DISABLED_ since
v2.0.0's first commit, and forcing it to run shows the path coming out shorter than the
track it is meant to follow.

PathSectionType::HL_SWATH is equally unfinished — never produced or consumed anywhere,
skipped by discretizeSwath(), unreachable through any public API. It is in this PR because
the fix produces it: the straight legs between rounded corners are headland passes, not
turns, and without the HL_SWATH half each would be a type discretizeSwath() refuses to
subdivide, leaving it a single waypoint.

1. Discretize HL_SWATH sections (83dc019)

discretizeSwath() only densified SWATH states. One condition, plus the doc comment.

No call path in the tree changes behaviour, because nothing produced the type.

2. Let appendSwath write the section type (e9a18f1)

void appendSwath(const Swath& swath, double cruise_speed);                        // existing
void appendSwath(const Swath& swath, double cruise_speed, PathSectionType type);  // added

The two-argument form delegates with SWATH. An overload rather than a default argument,
so the ABI is untouched.

setSwathType()/setTurnType() already exist and have no callers in the library — they
are there for the outside, and the third type had no counterpart.

If the preferred answer is to drop the enumerator instead: it is serialized as 3 by
serializePath, so removing it changes the file format, and telling a headland pass from
a swath is a real need — generateHeadlandSwaths returns rings, and turning one into a
drivable path is the next thing we need from the library.

3. Follow and round the connection track (9c3a06e)

planPathForConnection now walks the polyline: straight runs become HL_SWATH legs,
and only genuine corners go to createTurn. Corners too close together to take one at a
time are folded into a single maneuver; a corner a turn could only round by cutting past
cut_tol is left square instead. A connection whose track stays within a quarter of the operation width
of the straight hop, or one that reverses over a short hop, is still driven direct — the
u-turn between neighbouring swaths is the hop itself, and an arc through a 180-degree
vertex has no tangent length to round with.

Four details decide whether that produces corners or loops. Each was checked by reverting it
and confirming a test goes red:

  • The approach is sized from the radius the turn actually sweeps — the wider of
    getSmoothTurningRadius (public since Small API additions: Route::reverse, TurningBase::hasContinuousCurvature, public getSmoothTurningRadius #233; the clothoid ramps spend part of the
    deflection) and sqrt(rate * sweep) (a shallow corner never reaches full curvature). They
    cross around 50 degrees. Take only the first and a shallow corner starts its turn a metre
    early, cutting ground the covering legs either side of it need.
  • A turn is judged by how far it turns, not how long it is. A loop's extra 2*pi*R is a
    couple of metres at a small radius — inside any sane length budget, and smooth enough that
    no heading-step check sees it. Turning does not hide it, and it catches doubling-back S
    shapes too.
  • cut_tol is floored in turning radii, capped at the operation width. Tied to the
    width alone, an implement whose turning circle is close to its own width gets every corner
    refused; the cap stops a wide-turning one cutting corners it should leave square.
  • The tangent margin applies only to a continuous-curvature turn, being room for the
    clothoid lead-in. A discontinuous turn has nothing to ramp.

simplifyConnection is removed, body and private declaration. This closes the second half
of #231 by construction
— the angle-wrap bug lived there, and the new code uses
Point::getAngleDiffAbs throughout.

One more fix along the way: at a pinned route end taking a single corner the outgoing
reference point is the corner, so the lateral-offset bound collapsed to zero and refused a
corner the tangent bound allowed.

4. Tests (7f7b322)

fields2cover_pp_pp.planPathForConnection is enabled with its expectations untouched.

Nine new tests over behaviour that had no coverage: detour corners, tight jogs folded into
one S, neighbour u-turns, curved tracks that must not be flattened, corners left sharp
because rounding would cut too much, corners taken from the swath's heading not the track's,
open-ended route connections, shallow-corner approach floors, and corners too close to
round one at a time.

distanceToPath, maxHeadingStep, turnStarts and maxTurnSweep go into the checker.
distanceToPath measures to the polyline through the states rather than to the states
themselves — a straight run is a single state, so measuring to states alone would miss the
track between them. maxTurnSweep is the loop fence: it takes the widest excursion of a
turn's running signed heading change, so a corner or an S reads under half a revolution
while a loop runs past a full one.

The shallow-corner test bounds the approach on both sides: a turn that starts at the
corner has no tangent to turn in, and one that starts too far back leaves the leg early and
cuts ground the covering legs either side of it need.

One candidate detail was dropped after the same check — adding the clothoid ramp length to
the approach distance. With the turning fence in place it changed no output at all, and at a
swath junction it made the turn slightly wider.

Known limitations

The tuning constants (cut_tol's fractions, the u-turn thresholds, the span limit) are
constexpr in an anonymous namespace rather than parameters. f2c::pp::PathPlanning is
entirely static, so exposing them raises a static-vs-instance question that is wider than
this change. Making cut_tol a defaulted argument would be a sensible follow-up: how much
ground a machine may cut across depends on the field and on what the implement is doing, so
it is the one an operator would plausibly want to set.

Where a connection meets a swath, the entry pose is the swath's own end pose and cannot
slide back along it, so a continuous-curvature turn there has no approach room and swings
slightly wide before settling. How wide depends on the curvature rate: it is small at rates
a field machine uses and grows as the rate falls. Bounded and drivable, but not as tight as
a corner with room on both sides.

u33549 added 4 commits August 18, 2026 12:11
discretizeSwath() only densified SWATH states; HL_SWATH stayed a
single waypoint, so headland/corridor legs stored with that type
couldn't be subdivided. Neither type has ever been produced by F2C
itself (HL_SWATH has been dead since the v2.0.0 initial commit), so
no existing call path changes behavior.
The only public way to produce an HL_SWATH state was building a
PathState by hand and calling addState. appendSwath always hardcoded
SWATH. New overload takes the type explicitly; the 2-argument version
now delegates to it with SWATH, so the existing signature and ABI are
unchanged.
planPathForConnection routed every consecutive waypoint pair through
the turn planner, including straight legs, and simplifyConnection's
angle-wrap bug (fabs on a raw angle difference) mis-simplified
sharply-turning tracks. Replace both with a corner-by-corner planner:
straight runs become HL_SWATH legs, only genuine corners go through
createTurn, and corners too tight or too close together are folded or
left sharp rather than plotting a shortcut across ground the route
routed around.

Four details the geometry needs:

- The approach to a corner is sized from the radius the turn actually
  sweeps, which is the wider of two effects: the clothoid ramps spend
  part of the deflection (getSmoothTurningRadius, public since Fields2Cover#233),
  and a shallow corner never reaches full curvature at all, peaking at
  sqrt(rate * sweep). Take only the first and a shallow corner is
  planned from a radius it never drives, which starts the turn a metre
  early and cuts ground the legs either side of it are covering.
- A candidate turn is judged by how far it turns, not how long it is.
  A loop costs an extra 2*pi*R, which at a small turning radius is a
  couple of metres and hides inside any length budget, but it cannot
  hide in the turning itself.
- cut_tol is floored in turning radii and capped at the operation
  width, so a compact implement still gets room for a fillet while a
  wide-turning one keeps the corners it should leave square.
- The tangent margin is room for a clothoid lead-in, so it applies
  only to a continuous-curvature turn; a discontinuous one needs the
  plain tangent length and cutting more would only cut corner.

At a pinned route end taking a single corner there is no outgoing leg
-- the reference point is the corner itself -- so the lateral-offset
bound collapses to zero and would refuse a corner the tangent bound
allows. Skip it there.

Enables the fields2cover_pp_pp.planPathForConnection test, dead since
v2.0.0's first commit.
Nine tests over the corner-rounding path, which had no coverage before:
detour corners, tight jogs folded into one S, neighbour u-turns, curved
tracks that must not be flattened, corners left sharp because no turn
fits, corners taken from the swath's heading rather than the track's,
open-ended route connections, shallow-corner approach floors, and
corners too close to round one at a time.

Each bound here was checked by reverting the code it covers and
confirming the test goes red, so none of them is decorative. Two are
worth naming: the shallow-corner test bounds the approach on both
sides, because starting a turn too early cuts ground the covering legs
either side of it need; and maxTurnSweep is what catches a turn planner
answering with a loop, which is smooth, barely longer, and invisible to
every other measure here.

distanceToPath measures to the polyline through the states, not to the
states themselves: a straight run is one state, so measuring to states
alone would miss the track between them.
Copilot AI lite review requested due to automatic review settings August 18, 2026 13:16

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@u33549

u33549 commented Aug 18, 2026

Copy link
Copy Markdown
Contributor Author

Some before/after on the same scenarios, in case it helps reading the diff. Both columns run
the same code path on the same inputs — only this PR differs. F2CRobot(2.1, 2.5),
min_turning_radius 0.4, max_diff_curv 2.0, DubinsCurvesCC. Blue is the track the route
hands to the planner, green-to-black is the path, shaded from the start of the run to its end.

The connection is followed rather than cut across

A route whose connection detours over the top of two swaths. Before, the detour is skipped
and the path crosses at swath height; after, it follows the track and rounds the corners.

before after
1_corners_smoothed before 1_corners_smoothed after

The corners are 0.4 m of radius in a 40 m plot, so here is the top-left one at 8 m across.
Before, there is no path in frame at all — the route never goes there.

before after
z1_corner_TL before z1_corner_TL after

A curved connection stays curved

The connection here is a 40 m arc bulging 5 m off its chord. Before, the whole arc is
replaced by a single u-turn between the swath ends.

before after
4_curved_track_kept before 4_curved_track_kept after

Left junction at 10 m across. This is also the limitation from the description: the entry
pose is pinned to the swath's end, so the turn has no approach room on that side and swings
a little wide before settling. Worst case in these scenarios, at a curvature rate well below
what a field machine uses.

before after
z4_junction_L before z4_junction_L after

A corner too expensive to round is left square, not cut

Same field as the first pair, with an 8 m turning radius. There is room for the turn — the legs are 20 m and 30 m and the tangent needs 8 m — but at that radius the arc would cut almost 4 m off the corner, against a tolerance of half the operation width. So the corner stays square: a heading step the controller absorbs beats driving 4 m off the planned track.

before after
3_unroundable_stays_sharp before 3_unroundable_stays_sharp after

A decomposed field

A chaotic shape as a practical example

before after
7_comb_field before 7_comb_field after

@Gonzalo-Mier

Copy link
Copy Markdown
Member

It looks super nice the changes! Thank you really much for all your efforts.

I asked to move a bit some functions, but the logic seems solid.

Thank you again @u33549

@u33549 u33549 changed the title Follow connection polylines instead of cutting across them (#231) Follow connection polylines instead of cutting across them Aug 19, 2026
@u33549

u33549 commented Aug 19, 2026

Copy link
Copy Markdown
Contributor Author

@Gonzalo-Mier thank you, glad the approach reads well!

I can't see the comments about moving the functions on my side the diff shows none.

Happy to do the moves as soon as I can read them.

@Gonzalo-Mier

Copy link
Copy Markdown
Member

@Gonzalo-Mier thank you, glad the approach reads well!

I can't see the comments about moving the functions on my side the diff shows none.

Happy to do the moves as soon as I can read them.

Sorry, I forgot to send them

@u33549

u33549 commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Two structural questions before I do, since they change the shape of the diff:

1. getSmoothTurningRadius and the radius helper. The corner code picks a radius from getSmoothTurningRadius and from sqrt(linear_curv_change * sweep). Moving that to F2CRobot means getSmoothTurningRadius has to move too, and it needs end_of_clothoid from steering_functions — which would pull that dependency into types/. It is also
public API as of #233, so moving it is a break unless PathPlanning keeps a forwarder. Would you rather it moved to Robot (with a forwarder left behind), or stayed in PathPlanning?

2. Making the constants settable. PathPlanning's methods are all static, and fields2cover.cpp calls them as PathPlanning::planPath(...) in three places. Settable members mean the class gains state, so those calls become instance calls. Fine by me — I just want to confirm you are happy with PathPlanning becoming instantiable before I
change the facade.

My plan otherwise: the corner-cut tolerance onto Robot (it is a property of the machine and the implement), the rest of the tuning onto PathPlanning, pointAlong onto Point, the deviation and straight-leg helpers onto Path, toVectorPoint onto MultiPoint, and appendRoundedTrack split up. The size_t return is a sharp-corner count nothing reads — I'll drop it and make it void.

@Gonzalo-Mier

Copy link
Copy Markdown
Member

Hi @u33549,

Answering to your message:

  1. It is okay to move that dependence to F2CRobot. You can also create a new function with that logic in F2CRobot, and keep the function getSmoothTurningRadius in f2c::pp::PathPlanning to keep the ABI.
  2. Those parameters should be setteable, but shouldn't be placed in f2c::pp::PathPlanning. Maybe a better place can be F2CRobot.

u33549 added 4 commits August 20, 2026 12:17
Following a connection's track needs a handful of plain geometry that has
nothing to do with path planning: a point a given way along a ray, the
points of a geometry as a vector, appending a straight leg to a path, and
how far a path strays from a line.

Point::getPointAlong, MultiPoint::toVectorPoint, LineString::toVectorPoint,
Path::appendStraight and Path::maxDistanceTo. appendStraight takes a speed
rather than a Robot, matching appendSwath -- Robot.h already includes
Path.h, so the dependency cannot run the other way.
getSmoothTurningRadius computes a property of the robot, and the corner
planner needs two more of the same kind: the radius a turn of a given
deflection is driven at, and the tolerances and thresholds that decide
whether a corner is rounded at all.

Robot::getSmoothTurningRadius and Robot::getTurnRadius, plus settable
parameters for the corner planner. The four that scale with the machine
are stored in real units and derived from the robot when unset -- an
operator sets "at most 1.25 m of corner may be cut", not a fraction --
following the turn_vel_ precedent already in the class.
The anonymous namespace was carrying general-purpose geometry and a block
of tuning constants that callers had no way to reach. Both now live on the
types they describe, so this file keeps only the cornering logic.

getSmoothTurningRadius stays on PathPlanning as a forwarder: it was made
public one release ago, and moving it outright would break callers.
At 185 lines the reasoning was hard to follow. Same logic, in the four
steps it was already doing: the deflection at each corner, the fold of
corners too close to take one at a time, the room a span leaves for a
maneuver, and the search for a turn that fits it.

No behaviour change.
@u33549

u33549 commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @Gonzalo-Mier,
PathPlanning::getSmoothTurningRadius stays as a forwarder, as you suggested.

Three places where I did not follow the letter of the review, each for a reason:

appendStraight takes a speed, not a Robot. Robot.h already includes Path.h, so Path cannot depend on Robot. It matches appendSwath(swath, cruise_speed).

The parameters that scale with the machine are stored in real units, not as the fractions they were. getMaxCornerCut() is metres, defaulting to a value derived from the turning radius and the operation width; likewise getDirectHopMaxDev, getUturnMaxHop, getTrackSimplifyTol. An operator setting "at most 1.25 m of corner may be cut" seemed more useful than exposing a 0.5 coefficient. Unset values derive from the robot, following the turn_vel_ precedent. The dimensionless ones (getLegShare, getRadiusMargin, getMinBackoffRadii, getUturnReachRadii, getMaxCornerSpan) are stored as they are.

toVectorPoint went on LineString as well as MultiPoint. The same loop appeared twice, two lines apart.

On the size_t: it was a count of corners left square, and nothing read it. Removed, so appendRoundedTrack returns void.

The wrapper still took F2CPath& and mutated it, the exact pattern the
review asked to move off of -- moving the logic onto Path only helped
if callers actually called the member function.
@u33549

u33549 commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor Author

One more: I'd resolved the thread about not mutating the passed-in F2CPath too early — moving the logic onto Path::appendStraight didn't help while a thin wrapper in this file still took F2CPath& and mutated it. Removed the wrapper in d2805e3; call sites use path.appendStraight(...) directly now.

@Gonzalo-Mier

Copy link
Copy Markdown
Member

One last thing before accepting it. You use comments with \\\, which are used by the documentation to explain what the functions do, but they read like independent comments. In this case you can make them just \\, or add a proper explanation to the function or the variable.

@u33549

u33549 commented Aug 21, 2026

Copy link
Copy Markdown
Contributor Author

I hope I've changed the comments correctly

@Gonzalo-Mier
Gonzalo-Mier merged commit c1eb452 into Fields2Cover:main Aug 22, 2026
60 checks passed
@Gonzalo-Mier

Copy link
Copy Markdown
Member

Awesome changes and awesome PR! Thank you a lot again @u33549

@u33549

u33549 commented Aug 22, 2026

Copy link
Copy Markdown
Contributor Author

@Gonzalo-Mier You're welcome, it was a pleasure for me. I have a few more changes planned here, and I'm happy to work together on v3 once they're done.

@u33549
u33549 deleted the dev/umutc/v2.1.0-devel/connection-tracking branch August 22, 2026 10:04
@u33549

u33549 commented Aug 22, 2026

Copy link
Copy Markdown
Contributor Author

I’d also like to share what we’ve done on LinkedIn—if you’re okay with that, of course. If you approve, should I post about this change now, or wait until everything is finished and post everything at once?

@Gonzalo-Mier

Copy link
Copy Markdown
Member

Feel free to post everywhere what you do for open-source! no need to ask for permission or approval. It's your own work, so be proud wherever you want 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants