From 1e9131e5085400320e16459d304c20937ccf84af Mon Sep 17 00:00:00 2001 From: Anael ORLINSKI Date: Wed, 2 Sep 2026 13:04:05 +0200 Subject: [PATCH] Intersections: compute sweep fields bottom-up along the status for overlapping segments The sweep fields of the left-endpoints in a tolerance square are computed in CompareH order, each from the segment below it in the sweep status. Windings propagate bottom-up along the status, so this is only correct when the two orders agree. For overlapping segments that start in the same point they need not: a segment can then read the windings of a neighbour that has not been computed yet, gets zeros, and every segment above the stack inherits the error. mergeOverlapping later recomputes the merged stack itself, but not the segments above it, so the result polygon walk arrives at a vertex on a boundary segment and finds no segment leaving it: "next node for result polygon is nil" in debug mode, a silently truncated contour otherwise. Compute a left-endpoint's fields only after those of the segment below it when that segment starts in the same point, and mark computed endpoints so a segment is never computed twice. Split pieces start unmarked. This is the failure behind #382: the stroke outline of a merged grid of nearly-exact cells, where the outlines of adjacent cells overlap exactly along shared edges. The fixture from that PR now settles to the outer square in debug mode. The regression test builds equivalent geometry from a seeded grid with 1e-17 corner noise; four seeds panic before this change and settle to a single square of area 1.44 after it. Not addressed: some noisier grids hit "first segment became vertical and needs reversal, but was already in the sweep status", which is a different failure. Co-Authored-By: Claude Fable 5.1 --- path_intersection.go | 29 +++++++++-- path_intersection_overlap_test.go | 84 +++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+), 5 deletions(-) create mode 100644 path_intersection_overlap_test.go diff --git a/path_intersection.go b/path_intersection.go index e6c5b4aa..ad61ef65 100644 --- a/path_intersection.go +++ b/path_intersection.go @@ -294,6 +294,7 @@ type SweepPoint struct { vertical bool // segment is vertical increasing bool // original direction is left-right (or bottom-top) overlapped bool // segment's overlapping was handled + swept bool // sweep fields have been computed for this left-endpoint } func (s *SweepPoint) InterpolateY(x float64) float64 { @@ -326,6 +327,7 @@ func (s *SweepPoint) SplitAt(z Point) (*SweepPoint, *SweepPoint) { *r, *l = *s.other, *s r.Point, l.Point = z, z r.end, l.end = false, false + r.swept, l.swept = false, false // update references r.other, s.other.other = s, l @@ -1659,8 +1661,29 @@ func (a eventSliceV) Swap(i, j int) { // a[i], a[j] = a[j], a[i] //} +// computeSweepFieldsInOrder computes the sweep fields of a non-vertical left-endpoint from the +// segment below it in the sweep status, computing that segment first when it starts in the same +// point and has not been computed yet. Left-endpoints of a tolerance square are visited in +// CompareH order, but windings propagate bottom-up along the sweep status, and for overlapping +// segments starting in the same point the two orders need not agree: a segment would then read +// the windings of a neighbour that has not been computed yet. +func (cur *SweepPoint) computeSweepFieldsInOrder(op pathOp, fillRule FillRule) { + if cur.swept { + return + } + var prev *SweepPoint + if node := cur.node.Prev(); node != nil { + prev = node.SweepPoint + if !prev.swept && prev.node != nil && prev.Point == cur.Point { + prev.computeSweepFieldsInOrder(op, fillRule) + } + } + cur.computeSweepFields(prev, op, fillRule) +} + func (cur *SweepPoint) computeSweepFields(prev *SweepPoint, op pathOp, fillRule FillRule) { // cur is left-endpoint + cur.swept = true if !cur.open { cur.selfWindings = 1 if !cur.increasing { @@ -2281,11 +2304,7 @@ func bentleyOttmann(ps, qs Paths, op pathOp, fillRule FillRule) Paths { event.computeSweepFields(s, op, fillRule) } } else { - var s *SweepPoint - if event.node.Prev() != nil { - s = event.node.Prev().SweepPoint - } - event.computeSweepFields(s, op, fillRule) + event.computeSweepFieldsInOrder(op, fillRule) } } } diff --git a/path_intersection_overlap_test.go b/path_intersection_overlap_test.go new file mode 100644 index 00000000..beae402a --- /dev/null +++ b/path_intersection_overlap_test.go @@ -0,0 +1,84 @@ +package canvas + +import ( + "math" + "math/rand" + "testing" +) + +// noisyGrid builds n×n adjacent cells of size 0.1 whose corners carry random noise of magnitude +// eps, mimicking floating-point drift in computed geometry such as Voronoi cells. +func noisyGrid(n int, eps float64, rng *rand.Rand) Paths { + var ps Paths + nz := func() float64 { return (rng.Float64()*2 - 1) * eps } + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + x, y := 0.05+0.1*float64(i), 0.05+0.1*float64(j) + p := &Path{} + p.MoveTo(x+nz(), y+nz()) + p.LineTo(x+0.1+nz(), y+nz()) + p.LineTo(x+0.1+nz(), y+0.1+nz()) + p.LineTo(x+nz(), y+0.1+nz()) + p.Close() + ps = append(ps, p) + } + } + return ps +} + +// TestSettleOverlappingStackOrder strokes a merged grid of nearly-exact cells, which settles the +// outline with Settle(Positive). The stroke outlines of adjacent cells overlap exactly along the shared edges, so the +// sweep sees stacks of identical segments starting in the same point. Windings must be computed +// bottom-up along the sweep status; computing them in the square's CompareH order instead reads +// a not-yet-computed neighbour, the windings above the stack come out wrong, and the result +// polygon walk finds no continuation ("next node for result polygon is nil" in debug mode, a +// silently truncated contour otherwise). The settled outline of the 10×10 grid is the single +// outer square of side 1.2. +func TestSettleOverlappingStackOrder(t *testing.T) { + DebugPathIntersection = true + defer func() { DebugPathIntersection = false }() + + for _, seed := range []int64{6, 9, 12, 13} { + rng := rand.New(rand.NewSource(seed)) + merged := noisyGrid(10, 1e-17, rng).Merge() + + // Stroke settles the outline with Settle(Positive) + var res *Path + func() { + defer func() { + if r := recover(); r != nil { + t.Errorf("seed %d: panic: %v", seed, r) + } + }() + res = merged.Stroke(0.2, ButtCap, MiterJoin, 0.01) + }() + if res == nil { + continue + } + if n, a := len(res.Split()), polygonArea(res); n != 1 || math.Abs(a-1.44) > 1e-6 { + t.Errorf("seed %d: settled outline has %d subpaths and area %.6f, want 1 subpath of area 1.44", seed, n, a) + } + } +} + +// polygonArea returns the shoelace area of a flattened path (all subpaths). +func polygonArea(p *Path) float64 { + a := 0.0 + for _, sp := range p.Flatten(1e-3).Split() { + var pts []Point + d := sp.Data() + for i := 0; i < len(d); { + cmd := d[i] + n := cmdLen(cmd) + if cmd != CloseCmd { + pts = append(pts, Point{d[i+n-3], d[i+n-2]}) + } + i += n + } + for i := range pts { + j := (i + 1) % len(pts) + a += pts[i].X*pts[j].Y - pts[j].X*pts[i].Y + } + } + return a / 2 +}