Simplify.cpp revision cc90505674cd845fcbebd7e0654c3ff04a2e4f25
1/*
2 * Copyright 2012 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7#include "Simplify.h"
8
9#undef SkASSERT
10#define SkASSERT(cond) while (!(cond)) { sk_throw(); }
11
12// Terminology:
13// A Path contains one of more Contours
14// A Contour is made up of Segment array
15// A Segment is described by a Verb and a Point array with 2, 3, or 4 points
16// A Verb is one of Line, Quad(ratic), or Cubic
17// A Segment contains a Span array
18// A Span is describes a portion of a Segment using starting and ending T
19// T values range from 0 to 1, where 0 is the first Point in the Segment
20// An Edge is a Segment generated from a Span
21
22// FIXME: remove once debugging is complete
23#ifdef SK_DEBUG
24int gDebugMaxWindSum = SK_MaxS32;
25int gDebugMaxWindValue = SK_MaxS32;
26#endif
27
28#define DEBUG_UNUSED 0 // set to expose unused functions
29
30#if 0 // set to 1 for multiple thread -- no debugging
31
32const bool gRunTestsInOneThread = false;
33
34#define DEBUG_ACTIVE_SPANS 0
35#define DEBUG_ADD_INTERSECTING_TS 0
36#define DEBUG_ADD_T_PAIR 0
37#define DEBUG_CONCIDENT 0
38#define DEBUG_CROSS 0
39#define DEBUG_DUMP 0
40#define DEBUG_MARK_DONE 0
41#define DEBUG_PATH_CONSTRUCTION 0
42#define DEBUG_SORT 0
43#define DEBUG_WIND_BUMP 0
44#define DEBUG_WINDING 0
45
46#else
47
48const bool gRunTestsInOneThread = true;
49
50#define DEBUG_ACTIVE_SPANS 1
51#define DEBUG_ADD_INTERSECTING_TS 0
52#define DEBUG_ADD_T_PAIR 0
53#define DEBUG_CONCIDENT 01
54#define DEBUG_CROSS 1
55#define DEBUG_DUMP 1
56#define DEBUG_MARK_DONE 1
57#define DEBUG_PATH_CONSTRUCTION 1
58#define DEBUG_SORT 1
59#define DEBUG_WIND_BUMP 0
60#define DEBUG_WINDING 1
61
62#endif
63
64#if (DEBUG_ACTIVE_SPANS || DEBUG_CONCIDENT) && !DEBUG_DUMP
65#undef DEBUG_DUMP
66#define DEBUG_DUMP 1
67#endif
68
69#if DEBUG_DUMP
70static const char* kLVerbStr[] = {"", "line", "quad", "cubic"};
71// static const char* kUVerbStr[] = {"", "Line", "Quad", "Cubic"};
72static int gContourID;
73static int gSegmentID;
74#endif
75
76#ifndef DEBUG_TEST
77#define DEBUG_TEST 0
78#endif
79
80static int LineIntersect(const SkPoint a[2], const SkPoint b[2],
81        Intersections& intersections) {
82    const _Line aLine = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}};
83    const _Line bLine = {{b[0].fX, b[0].fY}, {b[1].fX, b[1].fY}};
84    return intersect(aLine, bLine, intersections.fT[0], intersections.fT[1]);
85}
86
87static int QuadLineIntersect(const SkPoint a[3], const SkPoint b[2],
88        Intersections& intersections) {
89    const Quadratic aQuad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY}};
90    const _Line bLine = {{b[0].fX, b[0].fY}, {b[1].fX, b[1].fY}};
91    intersect(aQuad, bLine, intersections);
92    return intersections.fUsed;
93}
94
95static int CubicLineIntersect(const SkPoint a[2], const SkPoint b[3],
96        Intersections& intersections) {
97    const Cubic aCubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY},
98            {a[3].fX, a[3].fY}};
99    const _Line bLine = {{b[0].fX, b[0].fY}, {b[1].fX, b[1].fY}};
100    return intersect(aCubic, bLine, intersections.fT[0], intersections.fT[1]);
101}
102
103static int QuadIntersect(const SkPoint a[3], const SkPoint b[3],
104        Intersections& intersections) {
105    const Quadratic aQuad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY}};
106    const Quadratic bQuad = {{b[0].fX, b[0].fY}, {b[1].fX, b[1].fY}, {b[2].fX, b[2].fY}};
107    intersect(aQuad, bQuad, intersections);
108    return intersections.fUsed;
109}
110
111static int CubicIntersect(const SkPoint a[4], const SkPoint b[4],
112        Intersections& intersections) {
113    const Cubic aCubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY},
114            {a[3].fX, a[3].fY}};
115    const Cubic bCubic = {{b[0].fX, b[0].fY}, {b[1].fX, b[1].fY}, {b[2].fX, b[2].fY},
116            {b[3].fX, b[3].fY}};
117    intersect(aCubic, bCubic, intersections);
118    return intersections.fUsed;
119}
120
121static int HLineIntersect(const SkPoint a[2], SkScalar left, SkScalar right,
122        SkScalar y, bool flipped, Intersections& intersections) {
123    const _Line aLine = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}};
124    return horizontalIntersect(aLine, left, right, y, flipped, intersections);
125}
126
127static int HQuadIntersect(const SkPoint a[3], SkScalar left, SkScalar right,
128        SkScalar y, bool flipped, Intersections& intersections) {
129    const Quadratic aQuad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY}};
130    return horizontalIntersect(aQuad, left, right, y, flipped, intersections);
131}
132
133static int HCubicIntersect(const SkPoint a[4], SkScalar left, SkScalar right,
134        SkScalar y, bool flipped, Intersections& intersections) {
135    const Cubic aCubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY},
136            {a[3].fX, a[3].fY}};
137    return horizontalIntersect(aCubic, left, right, y, flipped, intersections);
138}
139
140static int VLineIntersect(const SkPoint a[2], SkScalar top, SkScalar bottom,
141        SkScalar x, bool flipped, Intersections& intersections) {
142    const _Line aLine = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}};
143    return verticalIntersect(aLine, top, bottom, x, flipped, intersections);
144}
145
146static int VQuadIntersect(const SkPoint a[3], SkScalar top, SkScalar bottom,
147        SkScalar x, bool flipped, Intersections& intersections) {
148    const Quadratic aQuad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY}};
149    return verticalIntersect(aQuad, top, bottom, x, flipped, intersections);
150}
151
152static int VCubicIntersect(const SkPoint a[4], SkScalar top, SkScalar bottom,
153        SkScalar x, bool flipped, Intersections& intersections) {
154    const Cubic aCubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY},
155            {a[3].fX, a[3].fY}};
156    return verticalIntersect(aCubic, top, bottom, x, flipped, intersections);
157}
158
159static int (* const VSegmentIntersect[])(const SkPoint [], SkScalar ,
160        SkScalar , SkScalar , bool , Intersections& ) = {
161    NULL,
162    VLineIntersect,
163    VQuadIntersect,
164    VCubicIntersect
165};
166
167static void LineXYAtT(const SkPoint a[2], double t, SkPoint* out) {
168    const _Line line = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}};
169    double x, y;
170    xy_at_t(line, t, x, y);
171    out->fX = SkDoubleToScalar(x);
172    out->fY = SkDoubleToScalar(y);
173}
174
175static void QuadXYAtT(const SkPoint a[3], double t, SkPoint* out) {
176    const Quadratic quad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY}};
177    double x, y;
178    xy_at_t(quad, t, x, y);
179    out->fX = SkDoubleToScalar(x);
180    out->fY = SkDoubleToScalar(y);
181}
182
183static void CubicXYAtT(const SkPoint a[4], double t, SkPoint* out) {
184    const Cubic cubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY},
185            {a[3].fX, a[3].fY}};
186    double x, y;
187    xy_at_t(cubic, t, x, y);
188    out->fX = SkDoubleToScalar(x);
189    out->fY = SkDoubleToScalar(y);
190}
191
192static void (* const SegmentXYAtT[])(const SkPoint [], double , SkPoint* ) = {
193    NULL,
194    LineXYAtT,
195    QuadXYAtT,
196    CubicXYAtT
197};
198
199static SkScalar LineXAtT(const SkPoint a[2], double t) {
200    const _Line aLine = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}};
201    double x;
202    xy_at_t(aLine, t, x, *(double*) 0);
203    return SkDoubleToScalar(x);
204}
205
206static SkScalar QuadXAtT(const SkPoint a[3], double t) {
207    const Quadratic quad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY}};
208    double x;
209    xy_at_t(quad, t, x, *(double*) 0);
210    return SkDoubleToScalar(x);
211}
212
213static SkScalar CubicXAtT(const SkPoint a[4], double t) {
214    const Cubic cubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY},
215            {a[3].fX, a[3].fY}};
216    double x;
217    xy_at_t(cubic, t, x, *(double*) 0);
218    return SkDoubleToScalar(x);
219}
220
221static SkScalar (* const SegmentXAtT[])(const SkPoint [], double ) = {
222    NULL,
223    LineXAtT,
224    QuadXAtT,
225    CubicXAtT
226};
227
228static SkScalar LineYAtT(const SkPoint a[2], double t) {
229    const _Line aLine = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}};
230    double y;
231    xy_at_t(aLine, t, *(double*) 0, y);
232    return SkDoubleToScalar(y);
233}
234
235static SkScalar QuadYAtT(const SkPoint a[3], double t) {
236    const Quadratic quad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY}};
237    double y;
238    xy_at_t(quad, t, *(double*) 0, y);
239    return SkDoubleToScalar(y);
240}
241
242static SkScalar CubicYAtT(const SkPoint a[4], double t) {
243    const Cubic cubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY},
244            {a[3].fX, a[3].fY}};
245    double y;
246    xy_at_t(cubic, t, *(double*) 0, y);
247    return SkDoubleToScalar(y);
248}
249
250static SkScalar (* const SegmentYAtT[])(const SkPoint [], double ) = {
251    NULL,
252    LineYAtT,
253    QuadYAtT,
254    CubicYAtT
255};
256
257static SkScalar LineDXAtT(const SkPoint a[2], double ) {
258    return a[1].fX - a[0].fX;
259}
260
261static SkScalar QuadDXAtT(const SkPoint a[3], double t) {
262    const Quadratic quad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY}};
263    double x;
264    dxdy_at_t(quad, t, x, *(double*) 0);
265    return SkDoubleToScalar(x);
266}
267
268static SkScalar CubicDXAtT(const SkPoint a[4], double t) {
269    const Cubic cubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}, {a[2].fX, a[2].fY},
270            {a[3].fX, a[3].fY}};
271    double x;
272    dxdy_at_t(cubic, t, x, *(double*) 0);
273    return SkDoubleToScalar(x);
274}
275
276static SkScalar (* const SegmentDXAtT[])(const SkPoint [], double ) = {
277    NULL,
278    LineDXAtT,
279    QuadDXAtT,
280    CubicDXAtT
281};
282
283static void LineSubDivide(const SkPoint a[2], double startT, double endT,
284        SkPoint sub[2]) {
285    const _Line aLine = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}};
286    _Line dst;
287    sub_divide(aLine, startT, endT, dst);
288    sub[0].fX = SkDoubleToScalar(dst[0].x);
289    sub[0].fY = SkDoubleToScalar(dst[0].y);
290    sub[1].fX = SkDoubleToScalar(dst[1].x);
291    sub[1].fY = SkDoubleToScalar(dst[1].y);
292}
293
294static void QuadSubDivide(const SkPoint a[3], double startT, double endT,
295        SkPoint sub[3]) {
296    const Quadratic aQuad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
297            {a[2].fX, a[2].fY}};
298    Quadratic dst;
299    sub_divide(aQuad, startT, endT, dst);
300    sub[0].fX = SkDoubleToScalar(dst[0].x);
301    sub[0].fY = SkDoubleToScalar(dst[0].y);
302    sub[1].fX = SkDoubleToScalar(dst[1].x);
303    sub[1].fY = SkDoubleToScalar(dst[1].y);
304    sub[2].fX = SkDoubleToScalar(dst[2].x);
305    sub[2].fY = SkDoubleToScalar(dst[2].y);
306}
307
308static void CubicSubDivide(const SkPoint a[4], double startT, double endT,
309        SkPoint sub[4]) {
310    const Cubic aCubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
311            {a[2].fX, a[2].fY}, {a[3].fX, a[3].fY}};
312    Cubic dst;
313    sub_divide(aCubic, startT, endT, dst);
314    sub[0].fX = SkDoubleToScalar(dst[0].x);
315    sub[0].fY = SkDoubleToScalar(dst[0].y);
316    sub[1].fX = SkDoubleToScalar(dst[1].x);
317    sub[1].fY = SkDoubleToScalar(dst[1].y);
318    sub[2].fX = SkDoubleToScalar(dst[2].x);
319    sub[2].fY = SkDoubleToScalar(dst[2].y);
320    sub[3].fX = SkDoubleToScalar(dst[3].x);
321    sub[3].fY = SkDoubleToScalar(dst[3].y);
322}
323
324static void (* const SegmentSubDivide[])(const SkPoint [], double , double ,
325        SkPoint []) = {
326    NULL,
327    LineSubDivide,
328    QuadSubDivide,
329    CubicSubDivide
330};
331
332#if DEBUG_UNUSED
333static void QuadSubBounds(const SkPoint a[3], double startT, double endT,
334        SkRect& bounds) {
335    SkPoint dst[3];
336    QuadSubDivide(a, startT, endT, dst);
337    bounds.fLeft = bounds.fRight = dst[0].fX;
338    bounds.fTop = bounds.fBottom = dst[0].fY;
339    for (int index = 1; index < 3; ++index) {
340        bounds.growToInclude(dst[index].fX, dst[index].fY);
341    }
342}
343
344static void CubicSubBounds(const SkPoint a[4], double startT, double endT,
345        SkRect& bounds) {
346    SkPoint dst[4];
347    CubicSubDivide(a, startT, endT, dst);
348    bounds.fLeft = bounds.fRight = dst[0].fX;
349    bounds.fTop = bounds.fBottom = dst[0].fY;
350    for (int index = 1; index < 4; ++index) {
351        bounds.growToInclude(dst[index].fX, dst[index].fY);
352    }
353}
354#endif
355
356static SkPath::Verb QuadReduceOrder(const SkPoint a[3],
357        SkTDArray<SkPoint>& reducePts) {
358    const Quadratic aQuad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
359            {a[2].fX, a[2].fY}};
360    Quadratic dst;
361    int order = reduceOrder(aQuad, dst);
362    if (order == 3) {
363        return SkPath::kQuad_Verb;
364    }
365    for (int index = 0; index < order; ++index) {
366        SkPoint* pt = reducePts.append();
367        pt->fX = SkDoubleToScalar(dst[index].x);
368        pt->fY = SkDoubleToScalar(dst[index].y);
369    }
370    return (SkPath::Verb) (order - 1);
371}
372
373static SkPath::Verb CubicReduceOrder(const SkPoint a[4],
374        SkTDArray<SkPoint>& reducePts) {
375    const Cubic aCubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
376            {a[2].fX, a[2].fY}, {a[3].fX, a[3].fY}};
377    Cubic dst;
378    int order = reduceOrder(aCubic, dst, kReduceOrder_QuadraticsAllowed);
379    if (order == 4) {
380        return SkPath::kCubic_Verb;
381    }
382    for (int index = 0; index < order; ++index) {
383        SkPoint* pt = reducePts.append();
384        pt->fX = SkDoubleToScalar(dst[index].x);
385        pt->fY = SkDoubleToScalar(dst[index].y);
386    }
387    return (SkPath::Verb) (order - 1);
388}
389
390static bool QuadIsLinear(const SkPoint a[3]) {
391    const Quadratic aQuad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
392            {a[2].fX, a[2].fY}};
393    return isLinear(aQuad, 0, 2);
394}
395
396static bool CubicIsLinear(const SkPoint a[4]) {
397    const Cubic aCubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
398            {a[2].fX, a[2].fY}, {a[3].fX, a[3].fY}};
399    return isLinear(aCubic, 0, 3);
400}
401
402static SkScalar LineLeftMost(const SkPoint a[2], double startT, double endT) {
403    const _Line aLine = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}};
404    double x[2];
405    xy_at_t(aLine, startT, x[0], *(double*) 0);
406    xy_at_t(aLine, endT, x[1], *(double*) 0);
407    return SkMinScalar((float) x[0], (float) x[1]);
408}
409
410static SkScalar QuadLeftMost(const SkPoint a[3], double startT, double endT) {
411    const Quadratic aQuad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
412            {a[2].fX, a[2].fY}};
413    return (float) leftMostT(aQuad, startT, endT);
414}
415
416static SkScalar CubicLeftMost(const SkPoint a[4], double startT, double endT) {
417    const Cubic aCubic = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
418            {a[2].fX, a[2].fY}, {a[3].fX, a[3].fY}};
419    return (float) leftMostT(aCubic, startT, endT);
420}
421
422static SkScalar (* const SegmentLeftMost[])(const SkPoint [], double , double) = {
423    NULL,
424    LineLeftMost,
425    QuadLeftMost,
426    CubicLeftMost
427};
428
429#if DEBUG_UNUSED
430static bool IsCoincident(const SkPoint a[2], const SkPoint& above,
431        const SkPoint& below) {
432    const _Line aLine = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY}};
433    const _Line bLine = {{above.fX, above.fY}, {below.fX, below.fY}};
434    return implicit_matches_ulps(aLine, bLine, 32);
435}
436#endif
437
438class Segment;
439
440// sorting angles
441// given angles of {dx dy ddx ddy dddx dddy} sort them
442class Angle {
443public:
444    // FIXME: this is bogus for quads and cubics
445    // if the quads and cubics' line from end pt to ctrl pt are coincident,
446    // there's no obvious way to determine the curve ordering from the
447    // derivatives alone. In particular, if one quadratic's coincident tangent
448    // is longer than the other curve, the final control point can place the
449    // longer curve on either side of the shorter one.
450    // Using Bezier curve focus http://cagd.cs.byu.edu/~tom/papers/bezclip.pdf
451    // may provide some help, but nothing has been figured out yet.
452    bool operator<(const Angle& rh) const {
453        if ((fDy < 0) ^ (rh.fDy < 0)) {
454            return fDy < 0;
455        }
456        if (fDy == 0 && rh.fDy == 0 && fDx != rh.fDx) {
457            return fDx < rh.fDx;
458        }
459        SkScalar cmp = fDx * rh.fDy - rh.fDx * fDy;
460        if (cmp) {
461            return cmp < 0;
462        }
463        if ((fDDy < 0) ^ (rh.fDDy < 0)) {
464            return fDDy < 0;
465        }
466        if (fDDy == 0 && rh.fDDy == 0 && fDDx != rh.fDDx) {
467            return fDDx < rh.fDDx;
468        }
469        cmp = fDDx * rh.fDDy - rh.fDDx * fDDy;
470        if (cmp) {
471            return cmp < 0;
472        }
473        if ((fDDDy < 0) ^ (rh.fDDDy < 0)) {
474            return fDDDy < 0;
475        }
476        if (fDDDy == 0 && rh.fDDDy == 0) {
477            return fDDDx < rh.fDDDx;
478        }
479        return fDDDx * rh.fDDDy < rh.fDDDx * fDDDy;
480    }
481
482    double dx() const {
483        return fDx;
484    }
485
486    int end() const {
487        return fEnd;
488    }
489
490    bool firstBump(int sumWinding) const {
491        return sign() * sumWinding > 0;
492    }
493
494    bool isHorizontal() const {
495        return fDy == 0 && fDDy == 0 && fDDDy == 0;
496    }
497
498    // since all angles share a point, this needs to know which point
499    // is the common origin, i.e., whether the center is at pts[0] or pts[verb]
500    // practically, this should only be called by addAngle
501    void set(const SkPoint* pts, SkPath::Verb verb, const Segment* segment,
502            int start, int end) {
503        SkASSERT(start != end);
504        fSegment = segment;
505        fStart = start;
506        fEnd = end;
507        fDx = pts[1].fX - pts[0].fX; // b - a
508        fDy = pts[1].fY - pts[0].fY;
509        if (verb == SkPath::kLine_Verb) {
510            fDDx = fDDy = fDDDx = fDDDy = 0;
511            return;
512        }
513        fDDx = pts[2].fX - pts[1].fX - fDx; // a - 2b + c
514        fDDy = pts[2].fY - pts[1].fY - fDy;
515        if (verb == SkPath::kQuad_Verb) {
516            fDDDx = fDDDy = 0;
517            return;
518        }
519        fDDDx = pts[3].fX + 3 * (pts[1].fX - pts[2].fX) - pts[0].fX;
520        fDDDy = pts[3].fY + 3 * (pts[1].fY - pts[2].fY) - pts[0].fY;
521    }
522
523    // noncoincident quads/cubics may have the same initial angle
524    // as lines, so must sort by derivatives as well
525    // if flatness turns out to be a reasonable way to sort, use the below:
526    void setFlat(const SkPoint* pts, SkPath::Verb verb, Segment* segment,
527            int start, int end) {
528        fSegment = segment;
529        fStart = start;
530        fEnd = end;
531        fDx = pts[1].fX - pts[0].fX; // b - a
532        fDy = pts[1].fY - pts[0].fY;
533        if (verb == SkPath::kLine_Verb) {
534            fDDx = fDDy = fDDDx = fDDDy = 0;
535            return;
536        }
537        if (verb == SkPath::kQuad_Verb) {
538            int uplsX = FloatAsInt(pts[2].fX - pts[1].fY - fDx);
539            int uplsY = FloatAsInt(pts[2].fY - pts[1].fY - fDy);
540            int larger = std::max(abs(uplsX), abs(uplsY));
541            int shift = 0;
542            double flatT;
543            SkPoint ddPt; // FIXME: get rid of copy (change fDD_ to point)
544            LineParameters implicitLine;
545            _Line tangent = {{pts[0].fX, pts[0].fY}, {pts[1].fX, pts[1].fY}};
546            implicitLine.lineEndPoints(tangent);
547            implicitLine.normalize();
548            while (larger > UlpsEpsilon * 1024) {
549                larger >>= 2;
550                ++shift;
551                flatT = 0.5 / (1 << shift);
552                QuadXYAtT(pts, flatT, &ddPt);
553                _Point _pt = {ddPt.fX, ddPt.fY};
554                double distance = implicitLine.pointDistance(_pt);
555                if (approximately_zero(distance)) {
556                    SkDebugf("%s ulps too small %1.9g\n", __FUNCTION__, distance);
557                    break;
558                }
559            }
560            flatT = 0.5 / (1 << shift);
561            QuadXYAtT(pts, flatT, &ddPt);
562            fDDx = ddPt.fX - pts[0].fX;
563            fDDy = ddPt.fY - pts[0].fY;
564            SkASSERT(fDDx != 0 || fDDy != 0);
565            fDDDx = fDDDy = 0;
566            return;
567        }
568        SkASSERT(0); // FIXME: add cubic case
569    }
570
571    Segment* segment() const {
572        return const_cast<Segment*>(fSegment);
573    }
574
575    int sign() const {
576        return SkSign32(fStart - fEnd);
577    }
578
579    int start() const {
580        return fStart;
581    }
582
583private:
584    SkScalar fDx;
585    SkScalar fDy;
586    SkScalar fDDx;
587    SkScalar fDDy;
588    SkScalar fDDDx;
589    SkScalar fDDDy;
590    const Segment* fSegment;
591    int fStart;
592    int fEnd;
593};
594
595static void sortAngles(SkTDArray<Angle>& angles, SkTDArray<Angle*>& angleList) {
596    int angleCount = angles.count();
597    int angleIndex;
598    angleList.setReserve(angleCount);
599    for (angleIndex = 0; angleIndex < angleCount; ++angleIndex) {
600        *angleList.append() = &angles[angleIndex];
601    }
602    QSort<Angle>(angleList.begin(), angleList.end() - 1);
603}
604
605// Bounds, unlike Rect, does not consider a line to be empty.
606struct Bounds : public SkRect {
607    static bool Intersects(const Bounds& a, const Bounds& b) {
608        return a.fLeft <= b.fRight && b.fLeft <= a.fRight &&
609                a.fTop <= b.fBottom && b.fTop <= a.fBottom;
610    }
611
612    void add(SkScalar left, SkScalar top, SkScalar right, SkScalar bottom) {
613        if (left < fLeft) {
614            fLeft = left;
615        }
616        if (top < fTop) {
617            fTop = top;
618        }
619        if (right > fRight) {
620            fRight = right;
621        }
622        if (bottom > fBottom) {
623            fBottom = bottom;
624        }
625    }
626
627    void add(const Bounds& toAdd) {
628        add(toAdd.fLeft, toAdd.fTop, toAdd.fRight, toAdd.fBottom);
629    }
630
631    bool isEmpty() {
632        return fLeft > fRight || fTop > fBottom
633                || fLeft == fRight && fTop == fBottom
634                || isnan(fLeft) || isnan(fRight)
635                || isnan(fTop) || isnan(fBottom);
636    }
637
638    void setCubicBounds(const SkPoint a[4]) {
639        _Rect dRect;
640        Cubic cubic  = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
641            {a[2].fX, a[2].fY}, {a[3].fX, a[3].fY}};
642        dRect.setBounds(cubic);
643        set((float) dRect.left, (float) dRect.top, (float) dRect.right,
644                (float) dRect.bottom);
645    }
646
647    void setQuadBounds(const SkPoint a[3]) {
648        const Quadratic quad = {{a[0].fX, a[0].fY}, {a[1].fX, a[1].fY},
649                {a[2].fX, a[2].fY}};
650        _Rect dRect;
651        dRect.setBounds(quad);
652        set((float) dRect.left, (float) dRect.top, (float) dRect.right,
653                (float) dRect.bottom);
654    }
655};
656
657struct Span {
658    Segment* fOther;
659    mutable SkPoint const* fPt; // lazily computed as needed
660    double fT;
661    double fOtherT; // value at fOther[fOtherIndex].fT
662    int fOtherIndex;  // can't be used during intersection
663    int fWindSum; // accumulated from contours surrounding this one
664    int fWindValue; // 0 == canceled; 1 == normal; >1 == coincident
665    bool fDone; // if set, this span to next higher T has been processed
666};
667
668class Segment {
669public:
670    Segment() {
671#if DEBUG_DUMP
672        fID = ++gSegmentID;
673#endif
674    }
675
676    bool activeAngle(int index, int& done, SkTDArray<Angle>& angles) const {
677        if (activeAngleInner(index, done, angles)) {
678            return true;
679        }
680        double referenceT = fTs[index].fT;
681        int lesser = index;
682        while (--lesser >= 0 && referenceT - fTs[lesser].fT < FLT_EPSILON) {
683            if (activeAngleOther(lesser, done, angles)) {
684                return true;
685            }
686        }
687        do {
688            if (activeAngleOther(index, done, angles)) {
689                return true;
690            }
691        } while (++index < fTs.count() && fTs[index].fT - referenceT < FLT_EPSILON);
692        return false;
693    }
694
695    bool activeAngleOther(int index, int& done, SkTDArray<Angle>& angles) const {
696        Span* span = &fTs[index];
697        Segment* other = span->fOther;
698        int oIndex = span->fOtherIndex;
699        return other->activeAngleInner(oIndex, done, angles);
700    }
701
702    bool activeAngleInner(int index, int& done, SkTDArray<Angle>& angles) const {
703        int next = nextSpan(index, 1);
704        if (next > 0) {
705            const Span& upSpan = fTs[index];
706            if (upSpan.fWindValue) {
707                addAngle(angles, index, next);
708                if (upSpan.fDone) {
709                    done++;
710                } else if (upSpan.fWindSum != SK_MinS32) {
711                    return true;
712                }
713            }
714        }
715        int prev = nextSpan(index, -1);
716        // edge leading into junction
717        if (prev >= 0) {
718            const Span& downSpan = fTs[prev];
719            if (downSpan.fWindValue) {
720                addAngle(angles, index, prev);
721                if (downSpan.fDone) {
722                    done++;
723                 } else if (downSpan.fWindSum != SK_MinS32) {
724                    return true;
725                }
726            }
727        }
728        return false;
729    }
730
731    SkScalar activeTop() const {
732        SkASSERT(!done());
733        int count = fTs.count();
734        SkScalar result = SK_ScalarMax;
735        bool lastDone = true;
736        for (int index = 0; index < count; ++index) {
737            bool done = fTs[index].fDone;
738            if (!done || !lastDone) {
739                SkScalar y = yAtT(index);
740                if (result > y) {
741                    result = y;
742                }
743            }
744            lastDone = done;
745        }
746        SkASSERT(result < SK_ScalarMax);
747        return result;
748    }
749
750    void addAngle(SkTDArray<Angle>& angles, int start, int end) const {
751        SkASSERT(start != end);
752        SkPoint edge[4];
753        (*SegmentSubDivide[fVerb])(fPts, fTs[start].fT, fTs[end].fT, edge);
754        Angle* angle = angles.append();
755        angle->set(edge, fVerb, this, start, end);
756    }
757
758    void addCancelOutsides(const SkTDArray<double>& outsideTs, Segment& other,
759            double oEnd) {
760        int tIndex = -1;
761        int tCount = fTs.count();
762        int oIndex = -1;
763        int oCount = other.fTs.count();
764        double tStart = outsideTs[0];
765        double oStart = outsideTs[1];
766        do {
767            ++tIndex;
768        } while (tStart - fTs[tIndex].fT >= FLT_EPSILON && tIndex < tCount);
769        int tIndexStart = tIndex;
770        do {
771            ++oIndex;
772        } while (oStart - other.fTs[oIndex].fT >= FLT_EPSILON && oIndex < oCount);
773        int oIndexStart = oIndex;
774        double nextT;
775        do {
776            nextT = fTs[++tIndex].fT;
777        } while (nextT < 1 && nextT - tStart < FLT_EPSILON);
778        double oNextT;
779        do {
780            oNextT = other.fTs[++oIndex].fT;
781        } while (oNextT < 1 && oNextT - oStart < FLT_EPSILON);
782        // at this point, spans before and after are at:
783        //  fTs[tIndexStart - 1], fTs[tIndexStart], fTs[tIndex]
784        // if tIndexStart == 0, no prior span
785        // if nextT == 1, no following span
786
787        // advance the span with zero winding
788        // if the following span exists (not past the end, non-zero winding)
789        // connect the two edges
790        if (!fTs[tIndexStart].fWindValue) {
791            if (tIndexStart > 0 && fTs[tIndexStart - 1].fWindValue) {
792    #if DEBUG_CONCIDENT
793                SkDebugf("%s 1 this=%d other=%d t [%d] %1.9g (%1.9g,%1.9g)\n",
794                        __FUNCTION__, fID, other.fID, tIndexStart - 1,
795                        fTs[tIndexStart - 1].fT, xyAtT(tIndexStart - 1).fX,
796                        xyAtT(tIndexStart - 1).fY);
797    #endif
798                SkASSERT(0); // incomplete
799            }
800            if (nextT < 1 && fTs[tIndex].fWindValue) {
801    #if DEBUG_CONCIDENT
802                SkDebugf("%s 2 this=%d other=%d t [%d] %1.9g (%1.9g,%1.9g)\n",
803                        __FUNCTION__, fID, other.fID, tIndex,
804                        fTs[tIndex].fT, xyAtT(tIndex).fX,
805                        xyAtT(tIndex).fY);
806    #endif
807                addTPair(fTs[tIndex].fT, other, other.fTs[oIndexStart].fT);
808            }
809        } else {
810            SkASSERT(!other.fTs[oIndexStart].fWindValue);
811            if (oIndexStart > 0 && other.fTs[oIndexStart - 1].fWindValue) {
812    #if DEBUG_CONCIDENT
813                SkDebugf("%s 3 this=%d other=%d t [%d] %1.9g (%1.9g,%1.9g)\n",
814                        __FUNCTION__, fID, other.fID, oIndexStart - 1,
815                        other.fTs[oIndexStart - 1].fT, other.xyAtT(oIndexStart - 1).fX,
816                        other.xyAtT(oIndexStart - 1).fY);
817    #endif
818                SkASSERT(0); // incomplete
819            }
820            if (oNextT < 1 && other.fTs[oIndex].fWindValue) {
821    #if DEBUG_CONCIDENT
822                SkDebugf("%s 4 this=%d other=%d t [%d] %1.9g (%1.9g,%1.9g)\n",
823                        __FUNCTION__, fID, other.fID, oIndex,
824                        other.fTs[oIndex].fT, other.xyAtT(oIndex).fX,
825                        other.xyAtT(oIndex).fY);
826                other.debugAddTPair(other.fTs[oIndex].fT, *this, fTs[tIndexStart].fT);
827    #endif
828            }
829        }
830    }
831
832    void addCoinOutsides(const SkTDArray<double>& outsideTs, Segment& other,
833            double oEnd) {
834        // walk this to outsideTs[0]
835        // walk other to outsideTs[1]
836        // if either is > 0, add a pointer to the other, copying adjacent winding
837        int tIndex = -1;
838        int oIndex = -1;
839        double tStart = outsideTs[0];
840        double oStart = outsideTs[1];
841        do {
842            ++tIndex;
843        } while (tStart - fTs[tIndex].fT >= FLT_EPSILON);
844        do {
845            ++oIndex;
846        } while (oStart - other.fTs[oIndex].fT >= FLT_EPSILON);
847        if (tIndex > 0 || oIndex > 0) {
848            addTPair(tStart, other, oStart);
849        }
850        tStart = fTs[tIndex].fT;
851        oStart = other.fTs[oIndex].fT;
852        do {
853            double nextT;
854            do {
855                nextT = fTs[++tIndex].fT;
856            } while (nextT - tStart < FLT_EPSILON);
857            tStart = nextT;
858            do {
859                nextT = other.fTs[++oIndex].fT;
860            } while (nextT - oStart < FLT_EPSILON);
861            oStart = nextT;
862            if (tStart == 1 && oStart == 1) {
863                break;
864            }
865            addTPair(tStart, other, oStart);
866        } while (tStart < 1 && oStart < 1 && oEnd - oStart >= FLT_EPSILON);
867    }
868
869    void addCubic(const SkPoint pts[4]) {
870        init(pts, SkPath::kCubic_Verb);
871        fBounds.setCubicBounds(pts);
872    }
873
874    // FIXME: this needs to defer add for aligned consecutive line segments
875    SkPoint addCurveTo(int start, int end, SkPath& path, bool active) {
876        SkPoint edge[4];
877        // OPTIMIZE? if not active, skip remainder and return xy_at_t(end)
878        (*SegmentSubDivide[fVerb])(fPts, fTs[start].fT, fTs[end].fT, edge);
879        if (active) {
880    #if DEBUG_PATH_CONSTRUCTION
881            SkDebugf("%s %s (%1.9g,%1.9g)", __FUNCTION__,
882                    kLVerbStr[fVerb], edge[1].fX, edge[1].fY);
883            if (fVerb > 1) {
884                SkDebugf(" (%1.9g,%1.9g)", edge[2].fX, edge[2].fY);
885            }
886            if (fVerb > 2) {
887                SkDebugf(" (%1.9g,%1.9g)", edge[3].fX, edge[3].fY);
888            }
889            SkDebugf("\n");
890    #endif
891            switch (fVerb) {
892                case SkPath::kLine_Verb:
893                    path.lineTo(edge[1].fX, edge[1].fY);
894                    break;
895                case SkPath::kQuad_Verb:
896                    path.quadTo(edge[1].fX, edge[1].fY, edge[2].fX, edge[2].fY);
897                    break;
898                case SkPath::kCubic_Verb:
899                    path.cubicTo(edge[1].fX, edge[1].fY, edge[2].fX, edge[2].fY,
900                            edge[3].fX, edge[3].fY);
901                    break;
902            }
903        }
904        return edge[fVerb];
905    }
906
907    void addLine(const SkPoint pts[2]) {
908        init(pts, SkPath::kLine_Verb);
909        fBounds.set(pts, 2);
910    }
911
912    const SkPoint& addMoveTo(int tIndex, SkPath& path, bool active) {
913        const SkPoint& pt = xyAtT(tIndex);
914        if (active) {
915    #if DEBUG_PATH_CONSTRUCTION
916            SkDebugf("%s (%1.9g,%1.9g)\n", __FUNCTION__, pt.fX, pt.fY);
917    #endif
918            path.moveTo(pt.fX, pt.fY);
919        }
920        return pt;
921    }
922
923    // add 2 to edge or out of range values to get T extremes
924    void addOtherT(int index, double otherT, int otherIndex) {
925        Span& span = fTs[index];
926        span.fOtherT = otherT;
927        span.fOtherIndex = otherIndex;
928    }
929
930    void addQuad(const SkPoint pts[3]) {
931        init(pts, SkPath::kQuad_Verb);
932        fBounds.setQuadBounds(pts);
933    }
934
935    // Defer all coincident edge processing until
936    // after normal intersections have been computed
937
938// no need to be tricky; insert in normal T order
939// resolve overlapping ts when considering coincidence later
940
941    // add non-coincident intersection. Resulting edges are sorted in T.
942    int addT(double newT, Segment* other) {
943        // FIXME: in the pathological case where there is a ton of intercepts,
944        //  binary search?
945        int insertedAt = -1;
946        size_t tCount = fTs.count();
947        for (size_t index = 0; index < tCount; ++index) {
948            // OPTIMIZATION: if there are three or more identical Ts, then
949            // the fourth and following could be further insertion-sorted so
950            // that all the edges are clockwise or counterclockwise.
951            // This could later limit segment tests to the two adjacent
952            // neighbors, although it doesn't help with determining which
953            // circular direction to go in.
954            if (newT < fTs[index].fT) {
955                insertedAt = index;
956                break;
957            }
958        }
959        Span* span;
960        if (insertedAt >= 0) {
961            span = fTs.insert(insertedAt);
962        } else {
963            insertedAt = tCount;
964            span = fTs.append();
965        }
966        span->fT = newT;
967        span->fOther = other;
968        span->fPt = NULL;
969        span->fWindSum = SK_MinS32;
970        span->fWindValue = 1;
971        if ((span->fDone = newT == 1)) {
972            ++fDoneSpans;
973        }
974        return insertedAt;
975    }
976
977    // set spans from start to end to decrement by one
978    // note this walks other backwards
979    // FIMXE: there's probably an edge case that can be constructed where
980    // two span in one segment are separated by float epsilon on one span but
981    // not the other, if one segment is very small. For this
982    // case the counts asserted below may or may not be enough to separate the
983    // spans. Even if the counts work out, what if the spanw aren't correctly
984    // sorted? It feels better in such a case to match the span's other span
985    // pointer since both coincident segments must contain the same spans.
986    void addTCancel(double startT, double endT, Segment& other,
987            double oStartT, double oEndT) {
988        SkASSERT(endT - startT >= FLT_EPSILON);
989        SkASSERT(oEndT - oStartT >= FLT_EPSILON);
990        int index = 0;
991        while (startT - fTs[index].fT >= FLT_EPSILON) {
992            ++index;
993        }
994        int oIndex = other.fTs.count();
995        while (other.fTs[--oIndex].fT - oEndT > -FLT_EPSILON)
996            ;
997        Span* test = &fTs[index];
998        Span* oTest = &other.fTs[oIndex];
999        SkTDArray<double> outsideTs;
1000        SkTDArray<double> oOutsideTs;
1001        do {
1002            bool decrement = test->fWindValue && oTest->fWindValue;
1003            bool track = test->fWindValue || oTest->fWindValue;
1004            Span* end = test;
1005            double startT = end->fT;
1006            double oStartT = oTest->fT;
1007            do {
1008                if (decrement) {
1009                    decrementSpan(end);
1010                } else if (track && end->fT < 1 && oStartT < 1) {
1011                    TrackOutside(outsideTs, end->fT, oStartT);
1012                }
1013                end = &fTs[++index];
1014            } while (end->fT - test->fT < FLT_EPSILON);
1015            Span* oTestStart = oTest;
1016            do {
1017                if (decrement) {
1018                    other.decrementSpan(oTestStart);
1019                } else if (track && oTestStart->fT < 1 && startT < 1) {
1020                    TrackOutside(oOutsideTs, oTestStart->fT, startT);
1021                }
1022                if (!oIndex) {
1023                    break;
1024                }
1025                oTestStart = &other.fTs[--oIndex];
1026            } while (oTest->fT - oTestStart->fT < FLT_EPSILON);
1027            test = end;
1028            oTest = oTestStart;
1029        } while (test->fT < endT - FLT_EPSILON);
1030        SkASSERT(!oIndex || oTest->fT <= oStartT - FLT_EPSILON);
1031        // FIXME: determine if canceled edges need outside ts added
1032        if (!done() && outsideTs.count()) {
1033            addCancelOutsides(outsideTs, other, oEndT);
1034        }
1035        if (!other.done() && oOutsideTs.count()) {
1036            other.addCancelOutsides(oOutsideTs, *this, endT);
1037        }
1038    }
1039
1040    // set spans from start to end to increment the greater by one and decrement
1041    // the lesser
1042    void addTCoincident(double startT, double endT, Segment& other,
1043            double oStartT, double oEndT) {
1044        SkASSERT(endT - startT >= FLT_EPSILON);
1045        SkASSERT(oEndT - oStartT >= FLT_EPSILON);
1046        int index = 0;
1047        while (startT - fTs[index].fT >= FLT_EPSILON) {
1048            ++index;
1049        }
1050        int oIndex = 0;
1051        while (oStartT - other.fTs[oIndex].fT >= FLT_EPSILON) {
1052            ++oIndex;
1053        }
1054        Span* test = &fTs[index];
1055        Span* oTest = &other.fTs[oIndex];
1056        SkTDArray<double> outsideTs;
1057        SkTDArray<double> xOutsideTs;
1058        SkTDArray<double> oOutsideTs;
1059        SkTDArray<double> oxOutsideTs;
1060        do {
1061            bool transfer = test->fWindValue && oTest->fWindValue;
1062            bool decrementOther = test->fWindValue >= oTest->fWindValue;
1063            Span* end = test;
1064            double startT = end->fT;
1065            int startIndex = index;
1066            double oStartT = oTest->fT;
1067            int oStartIndex = oIndex;
1068            do {
1069                if (transfer) {
1070                    if (decrementOther) {
1071                        SkASSERT(abs(end->fWindValue) < gDebugMaxWindValue);
1072                        ++(end->fWindValue);
1073                    } else if (decrementSpan(end)) {
1074                        TrackOutside(outsideTs, end->fT, oStartT);
1075                    }
1076                } else if (oTest->fWindValue) {
1077                    SkASSERT(!decrementOther);
1078                    if (startIndex > 0 && fTs[startIndex - 1].fWindValue) {
1079                        TrackOutside(xOutsideTs, end->fT, oStartT);
1080                    }
1081                }
1082                end = &fTs[++index];
1083            } while (end->fT - test->fT < FLT_EPSILON);
1084            Span* oEnd = oTest;
1085            do {
1086                if (transfer) {
1087                    if (!decrementOther) {
1088                        SkASSERT(abs(oEnd->fWindValue) < gDebugMaxWindValue);
1089                        ++(oEnd->fWindValue);
1090                    } else if (other.decrementSpan(oEnd)) {
1091                        TrackOutside(oOutsideTs, oEnd->fT, startT);
1092                    }
1093                } else if (test->fWindValue) {
1094                    SkASSERT(!decrementOther);
1095                    if (oStartIndex > 0 && other.fTs[oStartIndex - 1].fWindValue) {
1096                        SkASSERT(0); // track for later?
1097                    }
1098                }
1099                oEnd = &other.fTs[++oIndex];
1100            } while (oEnd->fT - oTest->fT < FLT_EPSILON);
1101            test = end;
1102            oTest = oEnd;
1103        } while (test->fT < endT - FLT_EPSILON);
1104        SkASSERT(oTest->fT < oEndT + FLT_EPSILON);
1105        SkASSERT(oTest->fT > oEndT - FLT_EPSILON);
1106        if (!done()) {
1107            if (outsideTs.count()) {
1108                addCoinOutsides(outsideTs, other, oEndT);
1109            }
1110            if (xOutsideTs.count()) {
1111                addCoinOutsides(xOutsideTs, other, oEndT);
1112            }
1113        }
1114        if (!other.done() && oOutsideTs.count()) {
1115            other.addCoinOutsides(oOutsideTs, *this, endT);
1116        }
1117    }
1118
1119    // FIXME: this doesn't prevent the same span from being added twice
1120    // fix in caller, assert here?
1121    void addTPair(double t, Segment& other, double otherT) {
1122        int tCount = fTs.count();
1123        for (int tIndex = 0; tIndex < tCount; ++tIndex) {
1124            const Span& span = fTs[tIndex];
1125            if (span.fT > t) {
1126                break;
1127            }
1128            if (span.fT == t && span.fOther == &other && span.fOtherT == otherT) {
1129#if DEBUG_ADD_T_PAIR
1130                SkDebugf("%s addTPair duplicate this=%d %1.9g other=%d %1.9g\n",
1131                        __FUNCTION__, fID, t, other.fID, otherT);
1132#endif
1133                return;
1134            }
1135        }
1136#if DEBUG_ADD_T_PAIR
1137        SkDebugf("%s addTPair this=%d %1.9g other=%d %1.9g\n",
1138                __FUNCTION__, fID, t, other.fID, otherT);
1139#endif
1140        int insertedAt = addT(t, &other);
1141        int otherInsertedAt = other.addT(otherT, this);
1142        addOtherT(insertedAt, otherT, otherInsertedAt);
1143        other.addOtherT(otherInsertedAt, t, insertedAt);
1144        Span& newSpan = fTs[insertedAt];
1145        if (insertedAt > 0) {
1146            const Span& lastSpan = fTs[insertedAt - 1];
1147            if (t - lastSpan.fT < FLT_EPSILON) {
1148                int tWind = lastSpan.fWindValue;
1149                newSpan.fWindValue = tWind;
1150                if (!tWind) {
1151                    newSpan.fDone = true;
1152                    ++fDoneSpans;
1153                }
1154            }
1155        }
1156        int oIndex = newSpan.fOtherIndex;
1157        if (oIndex > 0) {
1158            const Span& lastOther = other.fTs[oIndex - 1];
1159            if (otherT - lastOther.fT < FLT_EPSILON) {
1160                int oWind = lastOther.fWindValue;
1161                Span& otherSpan = other.fTs[oIndex];
1162                otherSpan.fWindValue = oWind;
1163                if (!oWind) {
1164                    otherSpan.fDone = true;
1165                    ++(other.fDoneSpans);
1166                }
1167            }
1168        }
1169    }
1170
1171    void addTwoAngles(int start, int end, SkTDArray<Angle>& angles) const {
1172        // add edge leading into junction
1173        if (fTs[SkMin32(end, start)].fWindValue > 0) {
1174            addAngle(angles, end, start);
1175        }
1176        // add edge leading away from junction
1177        int step = SkSign32(end - start);
1178        int tIndex = nextSpan(end, step);
1179        if (tIndex >= 0 && fTs[SkMin32(end, tIndex)].fWindValue > 0) {
1180            addAngle(angles, end, tIndex);
1181        }
1182    }
1183
1184    const Bounds& bounds() const {
1185        return fBounds;
1186    }
1187
1188    void buildAngles(int index, SkTDArray<Angle>& angles) const {
1189        double referenceT = fTs[index].fT;
1190        int lesser = index;
1191        while (--lesser >= 0 && referenceT - fTs[lesser].fT < FLT_EPSILON) {
1192            buildAnglesInner(lesser, angles);
1193        }
1194        do {
1195            buildAnglesInner(index, angles);
1196        } while (++index < fTs.count() && fTs[index].fT - referenceT < FLT_EPSILON);
1197    }
1198
1199    void buildAnglesInner(int index, SkTDArray<Angle>& angles) const {
1200        Span* span = &fTs[index];
1201        Segment* other = span->fOther;
1202    // if there is only one live crossing, and no coincidence, continue
1203    // in the same direction
1204    // if there is coincidence, the only choice may be to reverse direction
1205        // find edge on either side of intersection
1206        int oIndex = span->fOtherIndex;
1207        // if done == -1, prior span has already been processed
1208        int step = 1;
1209        int next = other->nextSpan(oIndex, step);
1210        if (next < 0) {
1211            step = -step;
1212            next = other->nextSpan(oIndex, step);
1213        }
1214        // add candidate into and away from junction
1215        other->addTwoAngles(next, oIndex, angles);
1216    }
1217
1218    bool cancels(const Segment& other) const {
1219        SkASSERT(fVerb == SkPath::kLine_Verb);
1220        SkASSERT(other.fVerb == SkPath::kLine_Verb);
1221        SkPoint dxy = fPts[0] - fPts[1];
1222        SkPoint odxy = other.fPts[0] - other.fPts[1];
1223        return dxy.fX * odxy.fX < 0 || dxy.fY * odxy.fY < 0;
1224    }
1225
1226    // figure out if the segment's ascending T goes clockwise or not
1227    // not enough context to write this as shown
1228    // instead, add all segments meeting at the top
1229    // sort them using buildAngleList
1230    // find the first in the sort
1231    // see if ascendingT goes to top
1232    bool clockwise(int /* tIndex */) const {
1233        SkASSERT(0); // incomplete
1234        return false;
1235    }
1236
1237    int crossedSpan(const SkPoint& basePt, SkScalar& bestY, double& hitT) const {
1238        int bestT = -1;
1239        SkScalar top = bounds().fTop;
1240        SkScalar bottom = bounds().fBottom;
1241        int end = 0;
1242        do {
1243            int start = end;
1244            end = nextSpan(start, 1);
1245            if (fTs[start].fWindValue == 0) {
1246                continue;
1247            }
1248            SkPoint edge[4];
1249            // OPTIMIZE: wrap this so that if start==0 end==fTCount-1 we can
1250            // work with the original data directly
1251            (*SegmentSubDivide[fVerb])(fPts, fTs[start].fT, fTs[end].fT, edge);
1252            // intersect ray starting at basePt with edge
1253            Intersections intersections;
1254            int pts = (*VSegmentIntersect[fVerb])(edge, top, bottom, basePt.fX,
1255                    false, intersections);
1256            if (pts == 0) {
1257                continue;
1258            }
1259            if (pts > 1 && fVerb == SkPath::kLine_Verb) {
1260            // if the intersection is edge on, wait for another one
1261                continue;
1262            }
1263            SkASSERT(pts == 1); // FIXME: more code required to disambiguate
1264            SkPoint pt;
1265            double foundT = intersections.fT[0][0];
1266            (*SegmentXYAtT[fVerb])(fPts, foundT, &pt);
1267            if (bestY < pt.fY) {
1268                bestY = pt.fY;
1269                bestT = foundT < 1 ? start : end;
1270                hitT = fTs[start].fT + (fTs[end].fT - fTs[start].fT) * foundT;
1271            }
1272        } while (fTs[end].fT != 1);
1273        return bestT;
1274    }
1275
1276    bool decrementSpan(Span* span) {
1277        SkASSERT(span->fWindValue > 0);
1278        if (--(span->fWindValue) == 0) {
1279            span->fDone = true;
1280            ++fDoneSpans;
1281            return true;
1282        }
1283        return false;
1284    }
1285
1286    bool done() const {
1287        SkASSERT(fDoneSpans <= fTs.count());
1288        return fDoneSpans == fTs.count();
1289    }
1290
1291    bool done(const Angle& angle) const {
1292        int start = angle.start();
1293        int end = angle.end();
1294        const Span& mSpan = fTs[SkMin32(start, end)];
1295        return mSpan.fDone;
1296    }
1297
1298    // so the span needs to contain the pairing info found here
1299    // this should include the winding computed for the edge, and
1300    //  what edge it connects to, and whether it is discarded
1301    //  (maybe discarded == abs(winding) > 1) ?
1302    // only need derivatives for duration of sorting, add a new struct
1303    // for pairings, remove extra spans that have zero length and
1304    //  reference an unused other
1305    // for coincident, the last span on the other may be marked done
1306    //  (always?)
1307
1308    // if loop is exhausted, contour may be closed.
1309    // FIXME: pass in close point so we can check for closure
1310
1311    // given a segment, and a sense of where 'inside' is, return the next
1312    // segment. If this segment has an intersection, or ends in multiple
1313    // segments, find the mate that continues the outside.
1314    // note that if there are multiples, but no coincidence, we can limit
1315    // choices to connections in the correct direction
1316
1317    // mark found segments as done
1318
1319    // start is the index of the beginning T of this edge
1320    // it is guaranteed to have an end which describes a non-zero length (?)
1321    // winding -1 means ccw, 1 means cw
1322    // firstFind allows coincident edges to be treated differently
1323    Segment* findNext(SkTDArray<Span*>& chase, int winding,
1324            int contourWinding, bool firstFind, bool active,
1325            const int startIndex, const int endIndex, int& nextStart,
1326            int& nextEnd, int& spanWinding) {
1327
1328        start here;
1329        // winding is a mess
1330        // try to simplify what we got
1331
1332        int flipped = 1;
1333        int sumWinding = winding + spanWinding;
1334        if (sumWinding == 0 || (false && contourWinding && !firstFind)) {
1335            sumWinding = spanWinding;
1336        }
1337        bool insideContour = contourWinding && contourWinding * sumWinding < 0;
1338        if (insideContour && (true || !firstFind)) {
1339            sumWinding = contourWinding;
1340        }
1341
1342    #if DEBUG_WINDING
1343        SkDebugf("%s winding=%d contourWinding=%d spanWinding=%d sumWinding=%d\n",
1344                __FUNCTION__, winding, contourWinding, spanWinding, sumWinding);
1345    #endif
1346        SkASSERT(startIndex != endIndex);
1347        int count = fTs.count();
1348        SkASSERT(startIndex < endIndex ? startIndex < count - 1
1349                : startIndex > 0);
1350        int step = SkSign32(endIndex - startIndex);
1351        int end = nextSpan(startIndex, step);
1352        SkASSERT(end >= 0);
1353        Span* endSpan = &fTs[end];
1354        Segment* other;
1355        if (isSimple(end)) {
1356        // mark the smaller of startIndex, endIndex done, and all adjacent
1357        // spans with the same T value (but not 'other' spans)
1358            markDone(SkMin32(startIndex, endIndex), sumWinding);
1359            other = endSpan->fOther;
1360            nextStart = endSpan->fOtherIndex;
1361            double startT = other->fTs[nextStart].fT;
1362            nextEnd = nextStart;
1363            do {
1364                nextEnd += step;
1365            } while (fabs(startT - other->fTs[nextEnd].fT) < FLT_EPSILON);
1366            SkASSERT(step < 0 ? nextEnd >= 0 : nextEnd < other->fTs.count());
1367            return other;
1368        }
1369        // more than one viable candidate -- measure angles to find best
1370        SkTDArray<Angle> angles;
1371        SkASSERT(startIndex - endIndex != 0);
1372        SkASSERT((startIndex - endIndex < 0) ^ (step < 0));
1373        addTwoAngles(startIndex, end, angles);
1374        buildAngles(end, angles);
1375        SkTDArray<Angle*> sorted;
1376        sortAngles(angles, sorted);
1377        int angleCount = angles.count();
1378        int firstIndex = findStartingEdge(sorted, startIndex, end);
1379        SkASSERT(firstIndex >= 0);
1380    #if DEBUG_SORT
1381        debugShowSort(sorted, firstIndex, contourWinding, sumWinding);
1382    #endif
1383        bool doBump = sorted[firstIndex]->firstBump(sumWinding);
1384    #if DEBUG_WINDING
1385        SkDebugf("%s sumWinding=%d sign=%d (%sbump)\n", __FUNCTION__,
1386                sumWinding, sorted[firstIndex]->sign(), doBump ? "" : "no ");
1387    #endif
1388        bool innerSwap = active && (doBump || insideContour);
1389        int startWinding = sumWinding;
1390   //     SkASSERT(SkSign32(sumWinding) == SkSign32(winding) || winding == 0);
1391        if (doBump || insideContour) {
1392            sumWinding -= windBump(sorted[firstIndex]);
1393        }
1394        int nextIndex = firstIndex + 1;
1395        int lastIndex = firstIndex != 0 ? firstIndex : angleCount;
1396        const Angle* foundAngle = NULL;
1397        bool foundDone = false;
1398        // iterate through the angle, and compute everyone's winding
1399        bool firstEdge = true;
1400        bool flopped = false;
1401        Segment* nextSegment;
1402        do {
1403            if (nextIndex == angleCount) {
1404                nextIndex = 0;
1405            }
1406            const Angle* nextAngle = sorted[nextIndex];
1407            int maxWinding = sumWinding;
1408            nextSegment = nextAngle->segment();
1409            sumWinding -= nextSegment->windBump(nextAngle);
1410            SkASSERT(abs(sumWinding) <= gDebugMaxWindSum);
1411    #if DEBUG_WINDING
1412            SkDebugf("%s maxWinding=%d sumWinding=%d sign=%d\n", __FUNCTION__,
1413                    maxWinding, sumWinding, nextAngle->sign());
1414    #endif
1415            if (maxWinding * sumWinding < 0) {
1416                flipped = -flipped;
1417                flopped = true;
1418    #if DEBUG_WINDING
1419                SkDebugf("flipped sign %d %d\n", maxWinding, sumWinding);
1420    #endif
1421            }
1422            firstEdge = false;
1423            if (!sumWinding) {
1424                if (!active) {
1425                    markDone(SkMin32(startIndex, endIndex), startWinding);
1426                    nextSegment->markWinding(SkMin32(nextAngle->start(),
1427                                nextAngle->end()), maxWinding);
1428    #if DEBUG_WINDING
1429                    SkDebugf("%s inactive\n", __FUNCTION__);
1430    #endif
1431                    return NULL;
1432                }
1433                if (!foundAngle || foundDone) {
1434                    foundAngle = nextAngle;
1435                    foundDone = nextSegment->done(*nextAngle);
1436                    if (!flopped && maxWinding * startWinding < 0) {
1437                        flipped = -flipped;
1438            #if DEBUG_WINDING
1439                        SkDebugf("flopped sign %d %d\n", maxWinding, startWinding);
1440            #endif
1441                    }
1442                }
1443                continue;
1444            }
1445            if (!maxWinding && innerSwap && !foundAngle) {
1446                if (sumWinding * startWinding < 0 && flipped > 0) {
1447                    SkDebugf("%s flip?\n");
1448        //            flipped = -flipped;
1449                }
1450                foundAngle = nextAngle;
1451            }
1452            if (nextSegment->done()) {
1453                continue;
1454            }
1455            // if the winding is non-zero, nextAngle does not connect to
1456            // current chain. If we haven't done so already, mark the angle
1457            // as done, record the winding value, and mark connected unambiguous
1458            // segments as well.
1459            if (nextSegment->windSum(nextAngle) == SK_MinS32) {
1460                if (abs(maxWinding) < abs(sumWinding)) {
1461                    maxWinding = sumWinding;
1462                }
1463                Span* last;
1464                if (foundAngle || innerSwap) {
1465                    last = nextSegment->markAndChaseWinding(nextAngle, maxWinding);
1466                } else {
1467                    last = nextSegment->markAndChaseDone(nextAngle, maxWinding);
1468                }
1469                if (last) {
1470                    *chase.append() = last;
1471                }
1472            }
1473        } while (++nextIndex != lastIndex);
1474        SkASSERT(sorted[firstIndex]->segment() == this);
1475        markDone(SkMin32(startIndex, endIndex), startWinding);
1476        if (!foundAngle) {
1477            return NULL;
1478        }
1479        nextStart = foundAngle->start();
1480        nextEnd = foundAngle->end();
1481        nextSegment = foundAngle->segment();
1482        spanWinding = SkSign32(spanWinding) * flipped * nextSegment->windValue(
1483                SkMin32(nextStart, nextEnd));
1484        #if DEBUG_WINDING
1485            SkDebugf("%s spanWinding=%d\n", __FUNCTION__, spanWinding);
1486        #endif
1487        return nextSegment;
1488    }
1489
1490    int findStartingEdge(SkTDArray<Angle*>& sorted, int start, int end) {
1491        int angleCount = sorted.count();
1492        int firstIndex = -1;
1493        for (int angleIndex = 0; angleIndex < angleCount; ++angleIndex) {
1494            const Angle* angle = sorted[angleIndex];
1495            if (angle->segment() == this && angle->start() == end &&
1496                    angle->end() == start) {
1497                firstIndex = angleIndex;
1498                break;
1499            }
1500        }
1501        return firstIndex;
1502    }
1503
1504    // FIXME: this is tricky code; needs its own unit test
1505    void findTooCloseToCall(int /* winding */ ) { // FIXME: winding should be considered
1506        int count = fTs.count();
1507        if (count < 3) { // require t=0, x, 1 at minimum
1508            return;
1509        }
1510        int matchIndex = 0;
1511        int moCount;
1512        Span* match;
1513        Segment* mOther;
1514        do {
1515            match = &fTs[matchIndex];
1516            mOther = match->fOther;
1517            moCount = mOther->fTs.count();
1518            if (moCount >= 3) {
1519                break;
1520            }
1521            if (++matchIndex >= count) {
1522                return;
1523            }
1524        } while (true); // require t=0, x, 1 at minimum
1525        // OPTIMIZATION: defer matchPt until qualifying toCount is found?
1526        const SkPoint* matchPt = &xyAtT(match);
1527        // look for a pair of nearby T values that map to the same (x,y) value
1528        // if found, see if the pair of other segments share a common point. If
1529        // so, the span from here to there is coincident.
1530        for (int index = matchIndex + 1; index < count; ++index) {
1531            Span* test = &fTs[index];
1532            if (test->fDone) {
1533                continue;
1534            }
1535            Segment* tOther = test->fOther;
1536            int toCount = tOther->fTs.count();
1537            if (toCount < 3) { // require t=0, x, 1 at minimum
1538                continue;
1539            }
1540            const SkPoint* testPt = &xyAtT(test);
1541            if (*matchPt != *testPt) {
1542                matchIndex = index;
1543                moCount = toCount;
1544                match = test;
1545                mOther = tOther;
1546                matchPt = testPt;
1547                continue;
1548            }
1549            int moStart = -1;
1550            int moEnd = -1;
1551            double moStartT, moEndT;
1552            for (int moIndex = 0; moIndex < moCount; ++moIndex) {
1553                Span& moSpan = mOther->fTs[moIndex];
1554                if (moSpan.fDone) {
1555                    continue;
1556                }
1557                if (moSpan.fOther == this) {
1558                    if (moSpan.fOtherT == match->fT) {
1559                        moStart = moIndex;
1560                        moStartT = moSpan.fT;
1561                    }
1562                    continue;
1563                }
1564                if (moSpan.fOther == tOther) {
1565                    SkASSERT(moEnd == -1);
1566                    moEnd = moIndex;
1567                    moEndT = moSpan.fT;
1568                }
1569            }
1570            if (moStart < 0 || moEnd < 0) {
1571                continue;
1572            }
1573            // FIXME: if moStartT, moEndT are initialized to NaN, can skip this test
1574            if (moStartT == moEndT) {
1575                continue;
1576            }
1577            int toStart = -1;
1578            int toEnd = -1;
1579            double toStartT, toEndT;
1580            for (int toIndex = 0; toIndex < toCount; ++toIndex) {
1581                Span& toSpan = tOther->fTs[toIndex];
1582                if (toSpan.fOther == this) {
1583                    if (toSpan.fOtherT == test->fT) {
1584                        toStart = toIndex;
1585                        toStartT = toSpan.fT;
1586                    }
1587                    continue;
1588                }
1589                if (toSpan.fOther == mOther && toSpan.fOtherT == moEndT) {
1590                    SkASSERT(toEnd == -1);
1591                    toEnd = toIndex;
1592                    toEndT = toSpan.fT;
1593                }
1594            }
1595            // FIXME: if toStartT, toEndT are initialized to NaN, can skip this test
1596            if (toStart <= 0 || toEnd <= 0) {
1597                continue;
1598            }
1599            if (toStartT == toEndT) {
1600                continue;
1601            }
1602            // test to see if the segment between there and here is linear
1603            if (!mOther->isLinear(moStart, moEnd)
1604                    || !tOther->isLinear(toStart, toEnd)) {
1605                continue;
1606            }
1607            // FIXME: defer implementation until the rest works
1608            // this may share code with regular coincident detection
1609            SkASSERT(0);
1610        #if 0
1611            if (flipped) {
1612                mOther->addTCancel(moStart, moEnd, tOther, tStart, tEnd);
1613            } else {
1614                mOther->addTCoincident(moStart, moEnd, tOther, tStart, tEnd);
1615            }
1616        #endif
1617        }
1618    }
1619
1620    // OPTIMIZATION : for a pair of lines, can we compute points at T (cached)
1621    // and use more concise logic like the old edge walker code?
1622    // FIXME: this needs to deal with coincident edges
1623    Segment* findTop(int& tIndex, int& endIndex) {
1624        // iterate through T intersections and return topmost
1625        // topmost tangent from y-min to first pt is closer to horizontal
1626        SkASSERT(!done());
1627        int firstT;
1628        int lastT;
1629        SkPoint topPt;
1630        topPt.fY = SK_ScalarMax;
1631        int count = fTs.count();
1632        // see if either end is not done since we want smaller Y of the pair
1633        bool lastDone = true;
1634        for (int index = 0; index < count; ++index) {
1635            const Span& span = fTs[index];
1636            if (!span.fDone || !lastDone) {
1637                const SkPoint& intercept = xyAtT(&span);
1638                if (topPt.fY > intercept.fY || (topPt.fY == intercept.fY
1639                        && topPt.fX > intercept.fX)) {
1640                    topPt = intercept;
1641                    firstT = lastT = index;
1642                } else if (topPt == intercept) {
1643                    lastT = index;
1644                }
1645            }
1646            lastDone = span.fDone;
1647        }
1648        // sort the edges to find the leftmost
1649        int step = 1;
1650        int end = nextSpan(firstT, step);
1651        if (end == -1) {
1652            step = -1;
1653            end = nextSpan(firstT, step);
1654            SkASSERT(end != -1);
1655        }
1656        // if the topmost T is not on end, or is three-way or more, find left
1657        // look for left-ness from tLeft to firstT (matching y of other)
1658        SkTDArray<Angle> angles;
1659        SkASSERT(firstT - end != 0);
1660        addTwoAngles(end, firstT, angles);
1661        buildAngles(firstT, angles);
1662        SkTDArray<Angle*> sorted;
1663        sortAngles(angles, sorted);
1664        // skip edges that have already been processed
1665        firstT = -1;
1666        Segment* leftSegment;
1667        do {
1668            const Angle* angle = sorted[++firstT];
1669            leftSegment = angle->segment();
1670            tIndex = angle->end();
1671            endIndex = angle->start();
1672        } while (leftSegment->fTs[SkMin32(tIndex, endIndex)].fDone);
1673        return leftSegment;
1674    }
1675
1676    // FIXME: not crazy about this
1677    // when the intersections are performed, the other index is into an
1678    // incomplete array. as the array grows, the indices become incorrect
1679    // while the following fixes the indices up again, it isn't smart about
1680    // skipping segments whose indices are already correct
1681    // assuming we leave the code that wrote the index in the first place
1682    void fixOtherTIndex() {
1683        int iCount = fTs.count();
1684        for (int i = 0; i < iCount; ++i) {
1685            Span& iSpan = fTs[i];
1686            double oT = iSpan.fOtherT;
1687            Segment* other = iSpan.fOther;
1688            int oCount = other->fTs.count();
1689            for (int o = 0; o < oCount; ++o) {
1690                Span& oSpan = other->fTs[o];
1691                if (oT == oSpan.fT && this == oSpan.fOther) {
1692                    iSpan.fOtherIndex = o;
1693                    break;
1694                }
1695            }
1696        }
1697    }
1698
1699    // OPTIMIZATION: uses tail recursion. Unwise?
1700    Span* innerChaseDone(int index, int step, int winding) {
1701        int end = nextSpan(index, step);
1702        SkASSERT(end >= 0);
1703        if (multipleSpans(end)) {
1704            return &fTs[end];
1705        }
1706        const Span& endSpan = fTs[end];
1707        Segment* other = endSpan.fOther;
1708        index = endSpan.fOtherIndex;
1709        int otherEnd = other->nextSpan(index, step);
1710        Span* last = other->innerChaseDone(index, step, winding);
1711        other->markDone(SkMin32(index, otherEnd), winding);
1712        return last;
1713    }
1714
1715    Span* innerChaseWinding(int index, int step, int winding) {
1716        int end = nextSpan(index, step);
1717        SkASSERT(end >= 0);
1718        if (multipleSpans(end)) {
1719            return &fTs[end];
1720        }
1721        const Span& endSpan = fTs[end];
1722        Segment* other = endSpan.fOther;
1723        index = endSpan.fOtherIndex;
1724        int otherEnd = other->nextSpan(index, step);
1725        int min = SkMin32(index, otherEnd);
1726        if (other->fTs[min].fWindSum != SK_MinS32) {
1727            SkASSERT(other->fTs[min].fWindSum == winding);
1728            return NULL;
1729        }
1730        Span* last = other->innerChaseWinding(index, step, winding);
1731        other->markWinding(min, winding);
1732        return last;
1733    }
1734
1735    void init(const SkPoint pts[], SkPath::Verb verb) {
1736        fPts = pts;
1737        fVerb = verb;
1738        fDoneSpans = 0;
1739    }
1740
1741    bool intersected() const {
1742        return fTs.count() > 0;
1743    }
1744
1745    bool isLinear(int start, int end) const {
1746        if (fVerb == SkPath::kLine_Verb) {
1747            return true;
1748        }
1749        if (fVerb == SkPath::kQuad_Verb) {
1750            SkPoint qPart[3];
1751            QuadSubDivide(fPts, fTs[start].fT, fTs[end].fT, qPart);
1752            return QuadIsLinear(qPart);
1753        } else {
1754            SkASSERT(fVerb == SkPath::kCubic_Verb);
1755            SkPoint cPart[4];
1756            CubicSubDivide(fPts, fTs[start].fT, fTs[end].fT, cPart);
1757            return CubicIsLinear(cPart);
1758        }
1759    }
1760
1761    // OPTIMIZE: successive calls could start were the last leaves off
1762    // or calls could specialize to walk forwards or backwards
1763    bool isMissing(double startT) const {
1764        size_t tCount = fTs.count();
1765        for (size_t index = 0; index < tCount; ++index) {
1766            if (fabs(startT - fTs[index].fT) < FLT_EPSILON) {
1767                return false;
1768            }
1769        }
1770        return true;
1771    }
1772
1773    bool isSimple(int end) const {
1774        int count = fTs.count();
1775        if (count == 2) {
1776            return true;
1777        }
1778        double t = fTs[end].fT;
1779        if (t < FLT_EPSILON) {
1780            return fTs[1].fT >= FLT_EPSILON;
1781        }
1782        if (t > 1 - FLT_EPSILON) {
1783            return fTs[count - 2].fT <= 1 - FLT_EPSILON;
1784        }
1785        return false;
1786    }
1787
1788    bool isHorizontal() const {
1789        return fBounds.fTop == fBounds.fBottom;
1790    }
1791
1792    bool isVertical() const {
1793        return fBounds.fLeft == fBounds.fRight;
1794    }
1795
1796    SkScalar leftMost(int start, int end) const {
1797        return (*SegmentLeftMost[fVerb])(fPts, fTs[start].fT, fTs[end].fT);
1798    }
1799
1800    // this span is excluded by the winding rule -- chase the ends
1801    // as long as they are unambiguous to mark connections as done
1802    // and give them the same winding value
1803    Span* markAndChaseDone(const Angle* angle, int winding) {
1804        int index = angle->start();
1805        int endIndex = angle->end();
1806        int step = SkSign32(endIndex - index);
1807        Span* last = innerChaseDone(index, step, winding);
1808        markDone(SkMin32(index, endIndex), winding);
1809        return last;
1810    }
1811
1812    Span* markAndChaseWinding(const Angle* angle, int winding) {
1813        int index = angle->start();
1814        int endIndex = angle->end();
1815        int min = SkMin32(index, endIndex);
1816        int step = SkSign32(endIndex - index);
1817        Span* last = innerChaseWinding(index, step, winding);
1818        markWinding(min, winding);
1819        return last;
1820    }
1821
1822    // FIXME: this should also mark spans with equal (x,y)
1823    // This may be called when the segment is already marked done. While this
1824    // wastes time, it shouldn't do any more than spin through the T spans.
1825    // OPTIMIZATION: abort on first done found (assuming that this code is
1826    // always called to mark segments done).
1827    void markDone(int index, int winding) {
1828      //  SkASSERT(!done());
1829        double referenceT = fTs[index].fT;
1830        int lesser = index;
1831        while (--lesser >= 0 && referenceT - fTs[lesser].fT < FLT_EPSILON) {
1832            Span& span = fTs[lesser];
1833            if (span.fDone) {
1834                continue;
1835            }
1836        #if DEBUG_MARK_DONE
1837            const SkPoint& pt = xyAtT(&span);
1838            SkDebugf("%s segment=%d index=%d t=%1.9g pt=(%1.9g,%1.9g) wind=%d\n",
1839                    __FUNCTION__, fID, lesser, span.fT, pt.fX, pt.fY, winding);
1840        #endif
1841            span.fDone = true;
1842            SkASSERT(span.fWindSum == SK_MinS32 || span.fWindSum == winding);
1843            SkASSERT(abs(winding) <= gDebugMaxWindSum);
1844            span.fWindSum = winding;
1845            fDoneSpans++;
1846        }
1847        do {
1848            Span& span = fTs[index];
1849     //       SkASSERT(!span.fDone);
1850            if (span.fDone) {
1851                continue;
1852            }
1853        #if DEBUG_MARK_DONE
1854            const SkPoint& pt = xyAtT(&span);
1855            SkDebugf("%s segment=%d index=%d t=%1.9g pt=(%1.9g,%1.9g) wind=%d\n",
1856                    __FUNCTION__, fID, index, span.fT, pt.fX, pt.fY, winding);
1857        #endif
1858            span.fDone = true;
1859            SkASSERT(span.fWindSum == SK_MinS32 || span.fWindSum == winding);
1860            SkASSERT(abs(winding) <= gDebugMaxWindSum);
1861            span.fWindSum = winding;
1862            fDoneSpans++;
1863        } while (++index < fTs.count() && fTs[index].fT - referenceT < FLT_EPSILON);
1864    }
1865
1866    void markWinding(int index, int winding) {
1867    //    SkASSERT(!done());
1868        double referenceT = fTs[index].fT;
1869        int lesser = index;
1870        while (--lesser >= 0 && referenceT - fTs[lesser].fT < FLT_EPSILON) {
1871            Span& span = fTs[lesser];
1872            if (span.fDone) {
1873                continue;
1874            }
1875      //      SkASSERT(span.fWindValue == 1 || winding == 0);
1876            SkASSERT(span.fWindSum == SK_MinS32 || span.fWindSum == winding);
1877        #if DEBUG_MARK_DONE
1878            const SkPoint& pt = xyAtT(&span);
1879            SkDebugf("%s segment=%d index=%d t=%1.9g pt=(%1.9g,%1.9g) wind=%d\n",
1880                    __FUNCTION__, fID, lesser, span.fT, pt.fX, pt.fY, winding);
1881        #endif
1882            SkASSERT(abs(winding) <= gDebugMaxWindSum);
1883            span.fWindSum = winding;
1884        }
1885        do {
1886            Span& span = fTs[index];
1887     //       SkASSERT(!span.fDone || span.fCoincident);
1888            if (span.fDone) {
1889                continue;
1890            }
1891     //       SkASSERT(span.fWindValue == 1 || winding == 0);
1892            SkASSERT(span.fWindSum == SK_MinS32 || span.fWindSum == winding);
1893        #if DEBUG_MARK_DONE
1894            const SkPoint& pt = xyAtT(&span);
1895            SkDebugf("%s segment=%d index=%d t=%1.9g pt=(%1.9g,%1.9g) wind=%d\n",
1896                    __FUNCTION__, fID, index, span.fT, pt.fX, pt.fY, winding);
1897        #endif
1898            SkASSERT(abs(winding) <= gDebugMaxWindSum);
1899            span.fWindSum = winding;
1900        } while (++index < fTs.count() && fTs[index].fT - referenceT < FLT_EPSILON);
1901    }
1902
1903    // return span if when chasing, two or more radiating spans are not done
1904    // OPTIMIZATION: ? multiple spans is detected when there is only one valid
1905    // candidate and the remaining spans have windValue == 0 (canceled by
1906    // coincidence). The coincident edges could either be removed altogether,
1907    // or this code could be more complicated in detecting this case. Worth it?
1908    bool multipleSpans(int end) const {
1909        return end > 0 && end < fTs.count() - 1;
1910    }
1911
1912    // This has callers for two different situations: one establishes the end
1913    // of the current span, and one establishes the beginning of the next span
1914    // (thus the name). When this is looking for the end of the current span,
1915    // coincidence is found when the beginning Ts contain -step and the end
1916    // contains step. When it is looking for the beginning of the next, the
1917    // first Ts found can be ignored and the last Ts should contain -step.
1918    // OPTIMIZATION: probably should split into two functions
1919    int nextSpan(int from, int step) const {
1920        const Span& fromSpan = fTs[from];
1921        int count = fTs.count();
1922        int to = from;
1923        while (step > 0 ? ++to < count : --to >= 0) {
1924            const Span& span = fTs[to];
1925            if ((step > 0 ? span.fT - fromSpan.fT : fromSpan.fT - span.fT) < FLT_EPSILON) {
1926                continue;
1927            }
1928            return to;
1929        }
1930        return -1;
1931    }
1932
1933    const SkPoint* pts() const {
1934        return fPts;
1935    }
1936
1937    void reset() {
1938        init(NULL, (SkPath::Verb) -1);
1939        fBounds.set(SK_ScalarMax, SK_ScalarMax, SK_ScalarMax, SK_ScalarMax);
1940        fTs.reset();
1941    }
1942
1943    // OPTIMIZATION: mark as debugging only if used solely by tests
1944    const Span& span(int tIndex) const {
1945        return fTs[tIndex];
1946    }
1947
1948    int spanSign(int startIndex, int endIndex) const {
1949        return startIndex < endIndex ? -fTs[startIndex].fWindValue :
1950                fTs[endIndex].fWindValue;
1951    }
1952
1953    // OPTIMIZATION: mark as debugging only if used solely by tests
1954    double t(int tIndex) const {
1955        return fTs[tIndex].fT;
1956    }
1957
1958    static void TrackOutside(SkTDArray<double>& outsideTs, double end,
1959            double start) {
1960        int outCount = outsideTs.count();
1961        if (outCount == 0 || end - outsideTs[outCount - 2] >= FLT_EPSILON) {
1962            *outsideTs.append() = end;
1963            *outsideTs.append() = start;
1964        }
1965    }
1966
1967    void updatePts(const SkPoint pts[]) {
1968        fPts = pts;
1969    }
1970
1971    SkPath::Verb verb() const {
1972        return fVerb;
1973    }
1974
1975    int windBump(const Angle* angle) const {
1976        SkASSERT(angle->segment() == this);
1977        const Span& span = fTs[SkMin32(angle->start(), angle->end())];
1978        int result = angle->sign() * span.fWindValue;
1979#if DEBUG_WIND_BUMP
1980        SkDebugf("%s bump=%d\n", __FUNCTION__, result);
1981#endif
1982        return result;
1983    }
1984
1985    int windSum(int tIndex) const {
1986        return fTs[tIndex].fWindSum;
1987    }
1988
1989    int windSum(const Angle* angle) const {
1990        int start = angle->start();
1991        int end = angle->end();
1992        int index = SkMin32(start, end);
1993        return windSum(index);
1994    }
1995
1996    int windValue(int tIndex) const {
1997        return fTs[tIndex].fWindValue;
1998    }
1999
2000    int windValue(const Angle* angle) const {
2001        int start = angle->start();
2002        int end = angle->end();
2003        int index = SkMin32(start, end);
2004        return windValue(index);
2005    }
2006
2007    SkScalar xAtT(const Span* span) const {
2008        return xyAtT(span).fX;
2009    }
2010
2011    const SkPoint& xyAtT(int index) const {
2012        return xyAtT(&fTs[index]);
2013    }
2014
2015    const SkPoint& xyAtT(const Span* span) const {
2016        if (!span->fPt) {
2017            if (span->fT == 0) {
2018                span->fPt = &fPts[0];
2019            } else if (span->fT == 1) {
2020                span->fPt = &fPts[fVerb];
2021            } else {
2022                SkPoint* pt = fIntersections.append();
2023                (*SegmentXYAtT[fVerb])(fPts, span->fT, pt);
2024                span->fPt = pt;
2025            }
2026        }
2027        return *span->fPt;
2028    }
2029
2030    SkScalar yAtT(int index) const {
2031        return yAtT(&fTs[index]);
2032    }
2033
2034    SkScalar yAtT(const Span* span) const {
2035        return xyAtT(span).fY;
2036    }
2037
2038#if DEBUG_DUMP
2039    void dump() const {
2040        const char className[] = "Segment";
2041        const int tab = 4;
2042        for (int i = 0; i < fTs.count(); ++i) {
2043            SkPoint out;
2044            (*SegmentXYAtT[fVerb])(fPts, t(i), &out);
2045            SkDebugf("%*s [%d] %s.fTs[%d]=%1.9g (%1.9g,%1.9g) other=%d"
2046                    " otherT=%1.9g windSum=%d\n",
2047                    tab + sizeof(className), className, fID,
2048                    kLVerbStr[fVerb], i, fTs[i].fT, out.fX, out.fY,
2049                    fTs[i].fOther->fID, fTs[i].fOtherT, fTs[i].fWindSum);
2050        }
2051        SkDebugf("%*s [%d] fBounds=(l:%1.9g, t:%1.9g r:%1.9g, b:%1.9g)",
2052                tab + sizeof(className), className, fID,
2053                fBounds.fLeft, fBounds.fTop, fBounds.fRight, fBounds.fBottom);
2054    }
2055#endif
2056
2057#if DEBUG_CONCIDENT
2058    // assert if pair has not already been added
2059     void debugAddTPair(double t, const Segment& other, double otherT) {
2060        for (int i = 0; i < fTs.count(); ++i) {
2061            if (fTs[i].fT == t && fTs[i].fOther == &other && fTs[i].fOtherT == otherT) {
2062                return;
2063            }
2064        }
2065        SkASSERT(0);
2066     }
2067#endif
2068
2069#if DEBUG_CONCIDENT
2070    void debugShowTs() {
2071        SkDebugf("%s %d", __FUNCTION__, fID);
2072        for (int i = 0; i < fTs.count(); ++i) {
2073            SkDebugf(" [o=%d %1.9g (%1.9g,%1.9g) w=%d]", fTs[i].fOther->fID,
2074                    fTs[i].fT, xAtT(&fTs[i]), yAtT(&fTs[i]), fTs[i].fWindValue);
2075        }
2076        SkDebugf("\n");
2077    }
2078#endif
2079
2080#if DEBUG_ACTIVE_SPANS
2081    void debugShowActiveSpans(int contourID, int segmentIndex) {
2082        if (done()) {
2083            return;
2084        }
2085        for (int i = 0; i < fTs.count(); ++i) {
2086            if (fTs[i].fDone) {
2087                continue;
2088            }
2089            SkDebugf("%s contour=%d segment=%d (%d)", __FUNCTION__, contourID,
2090                     segmentIndex, fID);
2091            SkDebugf(" (%1.9g,%1.9g", fPts[0].fX, fPts[0].fY);
2092            for (int vIndex = 1; vIndex <= fVerb; ++vIndex) {
2093                SkDebugf(" %1.9g,%1.9g", fPts[vIndex].fX, fPts[vIndex].fY);
2094            }
2095            const Span* span = &fTs[i];
2096            SkDebugf(") fT=%d (%1.9g) (%1.9g,%1.9g)", i, fTs[i].fT,
2097                     xAtT(span), yAtT(i));
2098            const Segment* other = fTs[i].fOther;
2099            SkDebugf(" other=%d otherT=%1.9g otherIndex=%d", other->fID,
2100                     fTs[i].fOtherT, fTs[i].fOtherIndex);
2101            SkDebugf(" windSum=%d windValue=%d\n", fTs[i].fWindSum,
2102                     fTs[i].fWindValue);
2103        }
2104    }
2105#endif
2106
2107#if DEBUG_SORT
2108    void debugShowSort(const SkTDArray<Angle*>& angles, int first,
2109            int contourWinding, int sumWinding) {
2110        SkASSERT(angles[first]->segment() == this);
2111        bool doBump = angles[first]->firstBump(sumWinding);
2112        bool insideContour = contourWinding && contourWinding * sumWinding < 0;
2113        int windSum = insideContour ? contourWinding : sumWinding;
2114        int lastSum = windSum;
2115        if (insideContour || doBump) {
2116            windSum -= windBump(angles[first]);
2117        } else {
2118            lastSum += windBump(angles[first]);
2119        }
2120        int index = first;
2121        bool firstTime = true;
2122        do {
2123            const Angle& angle = *angles[index];
2124            const Segment& segment = *angle.segment();
2125            int start = angle.start();
2126            int end = angle.end();
2127            const Span& sSpan = segment.fTs[start];
2128            const Span& eSpan = segment.fTs[end];
2129            const Span& mSpan = segment.fTs[SkMin32(start, end)];
2130            if (firstTime) {
2131                firstTime = false;
2132            } else {
2133                lastSum = windSum;
2134                windSum -= segment.windBump(&angle);
2135            }
2136            SkDebugf("%s [%d] id=%d start=%d (%1.9g,%,1.9g) end=%d (%1.9g,%,1.9g)"
2137                     " sign=%d windValue=%d winding: %d->%d (max=%d) done=%d\n",
2138                     __FUNCTION__, index, segment.fID, start, segment.xAtT(&sSpan),
2139                     segment.yAtT(&sSpan), end, segment.xAtT(&eSpan),
2140                     segment.yAtT(&eSpan), angle.sign(), mSpan.fWindValue,
2141                     lastSum, windSum, abs(lastSum) > abs(windSum) ? lastSum :
2142                     windSum, mSpan.fDone);
2143            ++index;
2144            if (index == angles.count()) {
2145                index = 0;
2146            }
2147        } while (index != first);
2148    }
2149#endif
2150
2151private:
2152    const SkPoint* fPts;
2153    SkPath::Verb fVerb;
2154    Bounds fBounds;
2155    SkTDArray<Span> fTs; // two or more (always includes t=0 t=1)
2156    // OPTIMIZATION:if intersections array is a pointer, the it could only
2157    // be allocated as needed instead of always initialized -- though maybe
2158    // the initialization is lightweight enough that it hardly matters
2159    mutable SkTDArray<SkPoint> fIntersections;
2160    int fDoneSpans; // used for quick check that segment is finished
2161#if DEBUG_DUMP
2162    int fID;
2163#endif
2164};
2165
2166class Contour;
2167
2168struct Coincidence {
2169    Contour* fContours[2];
2170    int fSegments[2];
2171    double fTs[2][2];
2172};
2173
2174class Contour {
2175public:
2176    Contour() {
2177        reset();
2178#if DEBUG_DUMP
2179        fID = ++gContourID;
2180#endif
2181    }
2182
2183    bool operator<(const Contour& rh) const {
2184        return fBounds.fTop == rh.fBounds.fTop
2185                ? fBounds.fLeft < rh.fBounds.fLeft
2186                : fBounds.fTop < rh.fBounds.fTop;
2187    }
2188
2189    void addCoincident(int index, Contour* other, int otherIndex,
2190            const Intersections& ts, bool swap) {
2191        Coincidence& coincidence = *fCoincidences.append();
2192        coincidence.fContours[0] = this;
2193        coincidence.fContours[1] = other;
2194        coincidence.fSegments[0] = index;
2195        coincidence.fSegments[1] = otherIndex;
2196        coincidence.fTs[swap][0] = ts.fT[0][0];
2197        coincidence.fTs[swap][1] = ts.fT[0][1];
2198        coincidence.fTs[!swap][0] = ts.fT[1][0];
2199        coincidence.fTs[!swap][1] = ts.fT[1][1];
2200    }
2201
2202    void addCross(const Contour* crosser) {
2203#ifdef DEBUG_CROSS
2204        for (int index = 0; index < fCrosses.count(); ++index) {
2205            SkASSERT(fCrosses[index] != crosser);
2206        }
2207#endif
2208        *fCrosses.append() = crosser;
2209    }
2210
2211    void addCubic(const SkPoint pts[4]) {
2212        fSegments.push_back().addCubic(pts);
2213        fContainsCurves = true;
2214    }
2215
2216    int addLine(const SkPoint pts[2]) {
2217        fSegments.push_back().addLine(pts);
2218        return fSegments.count();
2219    }
2220
2221    void addOtherT(int segIndex, int tIndex, double otherT, int otherIndex) {
2222        fSegments[segIndex].addOtherT(tIndex, otherT, otherIndex);
2223    }
2224
2225    int addQuad(const SkPoint pts[3]) {
2226        fSegments.push_back().addQuad(pts);
2227        fContainsCurves = true;
2228        return fSegments.count();
2229    }
2230
2231    int addT(int segIndex, double newT, Contour* other, int otherIndex) {
2232        containsIntercepts();
2233        return fSegments[segIndex].addT(newT, &other->fSegments[otherIndex]);
2234    }
2235
2236    const Bounds& bounds() const {
2237        return fBounds;
2238    }
2239
2240    void complete() {
2241        setBounds();
2242        fContainsIntercepts = false;
2243    }
2244
2245    void containsIntercepts() {
2246        fContainsIntercepts = true;
2247    }
2248
2249    const Segment* crossedSegment(const SkPoint& basePt, SkScalar& bestY,
2250            int &tIndex, double& hitT) {
2251        int segmentCount = fSegments.count();
2252        const Segment* bestSegment = NULL;
2253        for (int test = 0; test < segmentCount; ++test) {
2254            Segment* testSegment = &fSegments[test];
2255            const SkRect& bounds = testSegment->bounds();
2256            if (bounds.fTop < bestY) {
2257                continue;
2258            }
2259            if (bounds.fTop > basePt.fY) {
2260                continue;
2261            }
2262            if (bounds.fLeft > basePt.fX) {
2263                continue;
2264            }
2265            if (bounds.fRight < basePt.fX) {
2266                continue;
2267            }
2268            double testHitT;
2269            int testT = testSegment->crossedSpan(basePt, bestY, testHitT);
2270            if (testT >= 0) {
2271                bestSegment = testSegment;
2272                tIndex = testT;
2273                hitT = testHitT;
2274            }
2275        }
2276        return bestSegment;
2277    }
2278
2279    bool crosses(const Contour* crosser) const {
2280        if (this == crosser) {
2281            return true;
2282        }
2283        for (int index = 0; index < fCrosses.count(); ++index) {
2284            if (fCrosses[index] == crosser) {
2285                return true;
2286            }
2287        }
2288        return false;
2289    }
2290
2291    void findTooCloseToCall(int winding) {
2292        int segmentCount = fSegments.count();
2293        for (int sIndex = 0; sIndex < segmentCount; ++sIndex) {
2294            fSegments[sIndex].findTooCloseToCall(winding);
2295        }
2296    }
2297
2298    void fixOtherTIndex() {
2299        int segmentCount = fSegments.count();
2300        for (int sIndex = 0; sIndex < segmentCount; ++sIndex) {
2301            fSegments[sIndex].fixOtherTIndex();
2302        }
2303    }
2304
2305    void reset() {
2306        fSegments.reset();
2307        fBounds.set(SK_ScalarMax, SK_ScalarMax, SK_ScalarMax, SK_ScalarMax);
2308        fContainsCurves = fContainsIntercepts = false;
2309        fWindingSum = SK_MinS32;
2310    }
2311
2312    void resolveCoincidence(int winding) {
2313        int count = fCoincidences.count();
2314        for (int index = 0; index < count; ++index) {
2315            Coincidence& coincidence = fCoincidences[index];
2316            Contour* thisContour = coincidence.fContours[0];
2317            Contour* otherContour = coincidence.fContours[1];
2318            int thisIndex = coincidence.fSegments[0];
2319            int otherIndex = coincidence.fSegments[1];
2320            Segment& thisOne = thisContour->fSegments[thisIndex];
2321            Segment& other = otherContour->fSegments[otherIndex];
2322        #if DEBUG_CONCIDENT
2323            thisOne.debugShowTs();
2324            other.debugShowTs();
2325        #endif
2326            double startT = coincidence.fTs[0][0];
2327            double endT = coincidence.fTs[0][1];
2328            if (startT > endT) {
2329                SkTSwap<double>(startT, endT);
2330            }
2331            SkASSERT(endT - startT >= FLT_EPSILON);
2332            double oStartT = coincidence.fTs[1][0];
2333            double oEndT = coincidence.fTs[1][1];
2334            if (oStartT > oEndT) {
2335                SkTSwap<double>(oStartT, oEndT);
2336            }
2337            SkASSERT(oEndT - oStartT >= FLT_EPSILON);
2338            if (winding > 0 || thisOne.cancels(other)) {
2339                        // make sure startT and endT have t entries
2340                if (thisOne.isMissing(startT) || other.isMissing(oEndT)) {
2341                    thisOne.addTPair(startT, other, oEndT);
2342                }
2343                if (thisOne.isMissing(endT) || other.isMissing(oStartT)) {
2344                    other.addTPair(oStartT, thisOne, endT);
2345                }
2346                thisOne.addTCancel(startT, endT, other, oStartT, oEndT);
2347            } else {
2348                if (thisOne.isMissing(startT) || other.isMissing(oStartT)) {
2349                    thisOne.addTPair(startT, other, oStartT);
2350                }
2351                if (thisOne.isMissing(endT) || other.isMissing(oEndT)) {
2352                    other.addTPair(oEndT, thisOne, endT);
2353                }
2354                thisOne.addTCoincident(startT, endT, other, oStartT, oEndT);
2355            }
2356        #if DEBUG_CONCIDENT
2357            thisOne.debugShowTs();
2358            other.debugShowTs();
2359        #endif
2360        }
2361    }
2362
2363    const SkTArray<Segment>& segments() {
2364        return fSegments;
2365    }
2366
2367    void setWinding(int winding) {
2368        SkASSERT(fWindingSum < 0 || fWindingSum == winding);
2369        fWindingSum = winding;
2370    }
2371
2372    // OPTIMIZATION: feel pretty uneasy about this. It seems like once again
2373    // we need to sort and walk edges in y, but that on the surface opens the
2374    // same can of worms as before. But then, this is a rough sort based on
2375    // segments' top, and not a true sort, so it could be ameniable to regular
2376    // sorting instead of linear searching. Still feel like I'm missing something
2377    Segment* topSegment(SkScalar& bestY) {
2378        int segmentCount = fSegments.count();
2379        SkASSERT(segmentCount > 0);
2380        int best = -1;
2381        Segment* bestSegment = NULL;
2382        while (++best < segmentCount) {
2383            Segment* testSegment = &fSegments[best];
2384            if (testSegment->done()) {
2385                continue;
2386            }
2387            bestSegment = testSegment;
2388            break;
2389        }
2390        if (!bestSegment) {
2391            return NULL;
2392        }
2393        SkScalar bestTop = bestSegment->activeTop();
2394        for (int test = best + 1; test < segmentCount; ++test) {
2395            Segment* testSegment = &fSegments[test];
2396            if (testSegment->done()) {
2397                continue;
2398            }
2399            if (testSegment->bounds().fTop > bestTop) {
2400                continue;
2401            }
2402            SkScalar testTop = testSegment->activeTop();
2403            if (bestTop > testTop) {
2404                bestTop = testTop;
2405                bestSegment = testSegment;
2406            }
2407        }
2408        bestY = bestTop;
2409        return bestSegment;
2410    }
2411
2412    int updateSegment(int index, const SkPoint* pts) {
2413        Segment& segment = fSegments[index];
2414        segment.updatePts(pts);
2415        return segment.verb() + 1;
2416    }
2417
2418    int windSum() {
2419        if (fWindingSum >= 0) {
2420            return fWindingSum;
2421        }
2422        // check peers
2423        int count = fCrosses.count();
2424        for (int index = 0; index < count; ++index) {
2425            const Contour* crosser = fCrosses[index];
2426            if (0 <= crosser->fWindingSum) {
2427                fWindingSum = crosser->fWindingSum;
2428                break;
2429            }
2430        }
2431        return fWindingSum;
2432    }
2433
2434#if DEBUG_TEST
2435    SkTArray<Segment>& debugSegments() {
2436        return fSegments;
2437    }
2438#endif
2439
2440#if DEBUG_DUMP
2441    void dump() {
2442        int i;
2443        const char className[] = "Contour";
2444        const int tab = 4;
2445        SkDebugf("%s %p (contour=%d)\n", className, this, fID);
2446        for (i = 0; i < fSegments.count(); ++i) {
2447            SkDebugf("%*s.fSegments[%d]:\n", tab + sizeof(className),
2448                    className, i);
2449            fSegments[i].dump();
2450        }
2451        SkDebugf("%*s.fBounds=(l:%1.9g, t:%1.9g r:%1.9g, b:%1.9g)\n",
2452                tab + sizeof(className), className,
2453                fBounds.fLeft, fBounds.fTop,
2454                fBounds.fRight, fBounds.fBottom);
2455        SkDebugf("%*s.fContainsIntercepts=%d\n", tab + sizeof(className),
2456                className, fContainsIntercepts);
2457        SkDebugf("%*s.fContainsCurves=%d\n", tab + sizeof(className),
2458                className, fContainsCurves);
2459    }
2460#endif
2461
2462#if DEBUG_ACTIVE_SPANS
2463    void debugShowActiveSpans() {
2464        for (int index = 0; index < fSegments.count(); ++index) {
2465            fSegments[index].debugShowActiveSpans(fID, index);
2466        }
2467    }
2468#endif
2469
2470protected:
2471    void setBounds() {
2472        int count = fSegments.count();
2473        if (count == 0) {
2474            SkDebugf("%s empty contour\n", __FUNCTION__);
2475            SkASSERT(0);
2476            // FIXME: delete empty contour?
2477            return;
2478        }
2479        fBounds = fSegments.front().bounds();
2480        for (int index = 1; index < count; ++index) {
2481            fBounds.add(fSegments[index].bounds());
2482        }
2483    }
2484
2485private:
2486    SkTArray<Segment> fSegments;
2487    SkTDArray<Coincidence> fCoincidences;
2488    SkTDArray<const Contour*> fCrosses;
2489    Bounds fBounds;
2490    bool fContainsIntercepts;
2491    bool fContainsCurves;
2492    int fWindingSum; // initial winding number outside
2493#if DEBUG_DUMP
2494    int fID;
2495#endif
2496};
2497
2498class EdgeBuilder {
2499public:
2500
2501EdgeBuilder(const SkPath& path, SkTArray<Contour>& contours)
2502    : fPath(path)
2503    , fCurrentContour(NULL)
2504    , fContours(contours)
2505{
2506#if DEBUG_DUMP
2507    gContourID = 0;
2508    gSegmentID = 0;
2509#endif
2510    walk();
2511}
2512
2513protected:
2514
2515void complete() {
2516    if (fCurrentContour && fCurrentContour->segments().count()) {
2517        fCurrentContour->complete();
2518        fCurrentContour = NULL;
2519    }
2520}
2521
2522void walk() {
2523    // FIXME:remove once we can access path pts directly
2524    SkPath::RawIter iter(fPath); // FIXME: access path directly when allowed
2525    SkPoint pts[4];
2526    SkPath::Verb verb;
2527    do {
2528        verb = iter.next(pts);
2529        *fPathVerbs.append() = verb;
2530        if (verb == SkPath::kMove_Verb) {
2531            *fPathPts.append() = pts[0];
2532        } else if (verb >= SkPath::kLine_Verb && verb <= SkPath::kCubic_Verb) {
2533            fPathPts.append(verb, &pts[1]);
2534        }
2535    } while (verb != SkPath::kDone_Verb);
2536    // FIXME: end of section to remove once path pts are accessed directly
2537
2538    SkPath::Verb reducedVerb;
2539    uint8_t* verbPtr = fPathVerbs.begin();
2540    const SkPoint* pointsPtr = fPathPts.begin();
2541    const SkPoint* finalCurveStart = NULL;
2542    const SkPoint* finalCurveEnd = NULL;
2543    while ((verb = (SkPath::Verb) *verbPtr++) != SkPath::kDone_Verb) {
2544        switch (verb) {
2545            case SkPath::kMove_Verb:
2546                complete();
2547                if (!fCurrentContour) {
2548                    fCurrentContour = fContours.push_back_n(1);
2549                    finalCurveEnd = pointsPtr++;
2550                    *fExtra.append() = -1; // start new contour
2551                }
2552                continue;
2553            case SkPath::kLine_Verb:
2554                // skip degenerate points
2555                if (pointsPtr[-1].fX != pointsPtr[0].fX
2556                        || pointsPtr[-1].fY != pointsPtr[0].fY) {
2557                    fCurrentContour->addLine(&pointsPtr[-1]);
2558                }
2559                break;
2560            case SkPath::kQuad_Verb:
2561
2562                reducedVerb = QuadReduceOrder(&pointsPtr[-1], fReducePts);
2563                if (reducedVerb == 0) {
2564                    break; // skip degenerate points
2565                }
2566                if (reducedVerb == 1) {
2567                    *fExtra.append() =
2568                            fCurrentContour->addLine(fReducePts.end() - 2);
2569                    break;
2570                }
2571                fCurrentContour->addQuad(&pointsPtr[-1]);
2572                break;
2573            case SkPath::kCubic_Verb:
2574                reducedVerb = CubicReduceOrder(&pointsPtr[-1], fReducePts);
2575                if (reducedVerb == 0) {
2576                    break; // skip degenerate points
2577                }
2578                if (reducedVerb == 1) {
2579                    *fExtra.append() =
2580                            fCurrentContour->addLine(fReducePts.end() - 2);
2581                    break;
2582                }
2583                if (reducedVerb == 2) {
2584                    *fExtra.append() =
2585                            fCurrentContour->addQuad(fReducePts.end() - 3);
2586                    break;
2587                }
2588                fCurrentContour->addCubic(&pointsPtr[-1]);
2589                break;
2590            case SkPath::kClose_Verb:
2591                SkASSERT(fCurrentContour);
2592                if (finalCurveStart && finalCurveEnd
2593                        && *finalCurveStart != *finalCurveEnd) {
2594                    *fReducePts.append() = *finalCurveStart;
2595                    *fReducePts.append() = *finalCurveEnd;
2596                    *fExtra.append() =
2597                            fCurrentContour->addLine(fReducePts.end() - 2);
2598                }
2599                complete();
2600                continue;
2601            default:
2602                SkDEBUGFAIL("bad verb");
2603                return;
2604        }
2605        finalCurveStart = &pointsPtr[verb - 1];
2606        pointsPtr += verb;
2607        SkASSERT(fCurrentContour);
2608    }
2609    complete();
2610    if (fCurrentContour && !fCurrentContour->segments().count()) {
2611        fContours.pop_back();
2612    }
2613    // correct pointers in contours since fReducePts may have moved as it grew
2614    int cIndex = 0;
2615    int extraCount = fExtra.count();
2616    SkASSERT(extraCount == 0 || fExtra[0] == -1);
2617    int eIndex = 0;
2618    int rIndex = 0;
2619    while (++eIndex < extraCount) {
2620        int offset = fExtra[eIndex];
2621        if (offset < 0) {
2622            ++cIndex;
2623            continue;
2624        }
2625        fCurrentContour = &fContours[cIndex];
2626        rIndex += fCurrentContour->updateSegment(offset - 1,
2627                &fReducePts[rIndex]);
2628    }
2629    fExtra.reset(); // we're done with this
2630}
2631
2632private:
2633    const SkPath& fPath;
2634    SkTDArray<SkPoint> fPathPts; // FIXME: point directly to path pts instead
2635    SkTDArray<uint8_t> fPathVerbs; // FIXME: remove
2636    Contour* fCurrentContour;
2637    SkTArray<Contour>& fContours;
2638    SkTDArray<SkPoint> fReducePts; // segments created on the fly
2639    SkTDArray<int> fExtra; // -1 marks new contour, > 0 offsets into contour
2640};
2641
2642class Work {
2643public:
2644    enum SegmentType {
2645        kHorizontalLine_Segment = -1,
2646        kVerticalLine_Segment = 0,
2647        kLine_Segment = SkPath::kLine_Verb,
2648        kQuad_Segment = SkPath::kQuad_Verb,
2649        kCubic_Segment = SkPath::kCubic_Verb,
2650    };
2651
2652    void addCoincident(Work& other, const Intersections& ts, bool swap) {
2653        fContour->addCoincident(fIndex, other.fContour, other.fIndex, ts, swap);
2654    }
2655
2656    // FIXME: does it make sense to write otherIndex now if we're going to
2657    // fix it up later?
2658    void addOtherT(int index, double otherT, int otherIndex) {
2659        fContour->addOtherT(fIndex, index, otherT, otherIndex);
2660    }
2661
2662    // Avoid collapsing t values that are close to the same since
2663    // we walk ts to describe consecutive intersections. Since a pair of ts can
2664    // be nearly equal, any problems caused by this should be taken care
2665    // of later.
2666    // On the edge or out of range values are negative; add 2 to get end
2667    int addT(double newT, const Work& other) {
2668        return fContour->addT(fIndex, newT, other.fContour, other.fIndex);
2669    }
2670
2671    bool advance() {
2672        return ++fIndex < fLast;
2673    }
2674
2675    SkScalar bottom() const {
2676        return bounds().fBottom;
2677    }
2678
2679    const Bounds& bounds() const {
2680        return fContour->segments()[fIndex].bounds();
2681    }
2682
2683    const SkPoint* cubic() const {
2684        return fCubic;
2685    }
2686
2687    void init(Contour* contour) {
2688        fContour = contour;
2689        fIndex = 0;
2690        fLast = contour->segments().count();
2691    }
2692
2693    bool isAdjacent(const Work& next) {
2694        return fContour == next.fContour && fIndex + 1 == next.fIndex;
2695    }
2696
2697    bool isFirstLast(const Work& next) {
2698        return fContour == next.fContour && fIndex == 0
2699                && next.fIndex == fLast - 1;
2700    }
2701
2702    SkScalar left() const {
2703        return bounds().fLeft;
2704    }
2705
2706    void promoteToCubic() {
2707        fCubic[0] = pts()[0];
2708        fCubic[2] = pts()[1];
2709        fCubic[3] = pts()[2];
2710        fCubic[1].fX = (fCubic[0].fX + fCubic[2].fX * 2) / 3;
2711        fCubic[1].fY = (fCubic[0].fY + fCubic[2].fY * 2) / 3;
2712        fCubic[2].fX = (fCubic[3].fX + fCubic[2].fX * 2) / 3;
2713        fCubic[2].fY = (fCubic[3].fY + fCubic[2].fY * 2) / 3;
2714    }
2715
2716    const SkPoint* pts() const {
2717        return fContour->segments()[fIndex].pts();
2718    }
2719
2720    SkScalar right() const {
2721        return bounds().fRight;
2722    }
2723
2724    ptrdiff_t segmentIndex() const {
2725        return fIndex;
2726    }
2727
2728    SegmentType segmentType() const {
2729        const Segment& segment = fContour->segments()[fIndex];
2730        SegmentType type = (SegmentType) segment.verb();
2731        if (type != kLine_Segment) {
2732            return type;
2733        }
2734        if (segment.isHorizontal()) {
2735            return kHorizontalLine_Segment;
2736        }
2737        if (segment.isVertical()) {
2738            return kVerticalLine_Segment;
2739        }
2740        return kLine_Segment;
2741    }
2742
2743    bool startAfter(const Work& after) {
2744        fIndex = after.fIndex;
2745        return advance();
2746    }
2747
2748    SkScalar top() const {
2749        return bounds().fTop;
2750    }
2751
2752    SkPath::Verb verb() const {
2753        return fContour->segments()[fIndex].verb();
2754    }
2755
2756    SkScalar x() const {
2757        return bounds().fLeft;
2758    }
2759
2760    bool xFlipped() const {
2761        return x() != pts()[0].fX;
2762    }
2763
2764    SkScalar y() const {
2765        return bounds().fTop;
2766    }
2767
2768    bool yFlipped() const {
2769        return y() != pts()[0].fY;
2770    }
2771
2772protected:
2773    Contour* fContour;
2774    SkPoint fCubic[4];
2775    int fIndex;
2776    int fLast;
2777};
2778
2779#if DEBUG_ADD_INTERSECTING_TS
2780static void debugShowLineIntersection(int pts, const Work& wt,
2781        const Work& wn, const double wtTs[2], const double wnTs[2]) {
2782    if (!pts) {
2783        SkDebugf("%s no intersect (%1.9g,%1.9g %1.9g,%1.9g) (%1.9g,%1.9g %1.9g,%1.9g)\n",
2784                __FUNCTION__, wt.pts()[0].fX, wt.pts()[0].fY,
2785                wt.pts()[1].fX, wt.pts()[1].fY, wn.pts()[0].fX, wn.pts()[0].fY,
2786                wn.pts()[1].fX, wn.pts()[1].fY);
2787        return;
2788    }
2789    SkPoint wtOutPt, wnOutPt;
2790    LineXYAtT(wt.pts(), wtTs[0], &wtOutPt);
2791    LineXYAtT(wn.pts(), wnTs[0], &wnOutPt);
2792    SkDebugf("%s wtTs[0]=%g (%g,%g, %g,%g) (%g,%g)",
2793            __FUNCTION__,
2794            wtTs[0], wt.pts()[0].fX, wt.pts()[0].fY,
2795            wt.pts()[1].fX, wt.pts()[1].fY, wtOutPt.fX, wtOutPt.fY);
2796    if (pts == 2) {
2797        SkDebugf(" wtTs[1]=%g", wtTs[1]);
2798    }
2799    SkDebugf(" wnTs[0]=%g (%g,%g, %g,%g) (%g,%g)",
2800            wnTs[0], wn.pts()[0].fX, wn.pts()[0].fY,
2801            wn.pts()[1].fX, wn.pts()[1].fY, wnOutPt.fX, wnOutPt.fY);
2802    if (pts == 2) {
2803        SkDebugf(" wnTs[1]=%g", wnTs[1]);
2804    }
2805    SkDebugf("\n");
2806}
2807#else
2808static void debugShowLineIntersection(int , const Work& ,
2809        const Work& , const double [2], const double [2]) {
2810}
2811#endif
2812
2813static bool addIntersectTs(Contour* test, Contour* next) {
2814
2815    if (test != next) {
2816        if (test->bounds().fBottom < next->bounds().fTop) {
2817            return false;
2818        }
2819        if (!Bounds::Intersects(test->bounds(), next->bounds())) {
2820            return true;
2821        }
2822    }
2823    Work wt;
2824    wt.init(test);
2825    bool foundCommonContour = test == next;
2826    do {
2827        Work wn;
2828        wn.init(next);
2829        if (test == next && !wn.startAfter(wt)) {
2830            continue;
2831        }
2832        do {
2833            if (!Bounds::Intersects(wt.bounds(), wn.bounds())) {
2834                continue;
2835            }
2836            int pts;
2837            Intersections ts;
2838            bool swap = false;
2839            switch (wt.segmentType()) {
2840                case Work::kHorizontalLine_Segment:
2841                    swap = true;
2842                    switch (wn.segmentType()) {
2843                        case Work::kHorizontalLine_Segment:
2844                        case Work::kVerticalLine_Segment:
2845                        case Work::kLine_Segment: {
2846                            pts = HLineIntersect(wn.pts(), wt.left(),
2847                                    wt.right(), wt.y(), wt.xFlipped(), ts);
2848                            debugShowLineIntersection(pts, wt, wn,
2849                                    ts.fT[1], ts.fT[0]);
2850                            break;
2851                        }
2852                        case Work::kQuad_Segment: {
2853                            pts = HQuadIntersect(wn.pts(), wt.left(),
2854                                    wt.right(), wt.y(), wt.xFlipped(), ts);
2855                            break;
2856                        }
2857                        case Work::kCubic_Segment: {
2858                            pts = HCubicIntersect(wn.pts(), wt.left(),
2859                                    wt.right(), wt.y(), wt.xFlipped(), ts);
2860                            break;
2861                        }
2862                        default:
2863                            SkASSERT(0);
2864                    }
2865                    break;
2866                case Work::kVerticalLine_Segment:
2867                    swap = true;
2868                    switch (wn.segmentType()) {
2869                        case Work::kHorizontalLine_Segment:
2870                        case Work::kVerticalLine_Segment:
2871                        case Work::kLine_Segment: {
2872                            pts = VLineIntersect(wn.pts(), wt.top(),
2873                                    wt.bottom(), wt.x(), wt.yFlipped(), ts);
2874                            debugShowLineIntersection(pts, wt, wn,
2875                                    ts.fT[1], ts.fT[0]);
2876                            break;
2877                        }
2878                        case Work::kQuad_Segment: {
2879                            pts = VQuadIntersect(wn.pts(), wt.top(),
2880                                    wt.bottom(), wt.x(), wt.yFlipped(), ts);
2881                            break;
2882                        }
2883                        case Work::kCubic_Segment: {
2884                            pts = VCubicIntersect(wn.pts(), wt.top(),
2885                                    wt.bottom(), wt.x(), wt.yFlipped(), ts);
2886                            break;
2887                        }
2888                        default:
2889                            SkASSERT(0);
2890                    }
2891                    break;
2892                case Work::kLine_Segment:
2893                    switch (wn.segmentType()) {
2894                        case Work::kHorizontalLine_Segment:
2895                            pts = HLineIntersect(wt.pts(), wn.left(),
2896                                    wn.right(), wn.y(), wn.xFlipped(), ts);
2897                            debugShowLineIntersection(pts, wt, wn,
2898                                    ts.fT[1], ts.fT[0]);
2899                            break;
2900                        case Work::kVerticalLine_Segment:
2901                            pts = VLineIntersect(wt.pts(), wn.top(),
2902                                    wn.bottom(), wn.x(), wn.yFlipped(), ts);
2903                            debugShowLineIntersection(pts, wt, wn,
2904                                    ts.fT[1], ts.fT[0]);
2905                            break;
2906                        case Work::kLine_Segment: {
2907                            pts = LineIntersect(wt.pts(), wn.pts(), ts);
2908                            debugShowLineIntersection(pts, wt, wn,
2909                                    ts.fT[1], ts.fT[0]);
2910                            break;
2911                        }
2912                        case Work::kQuad_Segment: {
2913                            swap = true;
2914                            pts = QuadLineIntersect(wn.pts(), wt.pts(), ts);
2915                            break;
2916                        }
2917                        case Work::kCubic_Segment: {
2918                            swap = true;
2919                            pts = CubicLineIntersect(wn.pts(), wt.pts(), ts);
2920                            break;
2921                        }
2922                        default:
2923                            SkASSERT(0);
2924                    }
2925                    break;
2926                case Work::kQuad_Segment:
2927                    switch (wn.segmentType()) {
2928                        case Work::kHorizontalLine_Segment:
2929                            pts = HQuadIntersect(wt.pts(), wn.left(),
2930                                    wn.right(), wn.y(), wn.xFlipped(), ts);
2931                            break;
2932                        case Work::kVerticalLine_Segment:
2933                            pts = VQuadIntersect(wt.pts(), wn.top(),
2934                                    wn.bottom(), wn.x(), wn.yFlipped(), ts);
2935                            break;
2936                        case Work::kLine_Segment: {
2937                            pts = QuadLineIntersect(wt.pts(), wn.pts(), ts);
2938                            break;
2939                        }
2940                        case Work::kQuad_Segment: {
2941                            pts = QuadIntersect(wt.pts(), wn.pts(), ts);
2942                            break;
2943                        }
2944                        case Work::kCubic_Segment: {
2945                            wt.promoteToCubic();
2946                            pts = CubicIntersect(wt.cubic(), wn.pts(), ts);
2947                            break;
2948                        }
2949                        default:
2950                            SkASSERT(0);
2951                    }
2952                    break;
2953                case Work::kCubic_Segment:
2954                    switch (wn.segmentType()) {
2955                        case Work::kHorizontalLine_Segment:
2956                            pts = HCubicIntersect(wt.pts(), wn.left(),
2957                                    wn.right(), wn.y(), wn.xFlipped(), ts);
2958                            break;
2959                        case Work::kVerticalLine_Segment:
2960                            pts = VCubicIntersect(wt.pts(), wn.top(),
2961                                    wn.bottom(), wn.x(), wn.yFlipped(), ts);
2962                            break;
2963                        case Work::kLine_Segment: {
2964                            pts = CubicLineIntersect(wt.pts(), wn.pts(), ts);
2965                            break;
2966                        }
2967                        case Work::kQuad_Segment: {
2968                            wn.promoteToCubic();
2969                            pts = CubicIntersect(wt.pts(), wn.cubic(), ts);
2970                            break;
2971                        }
2972                        case Work::kCubic_Segment: {
2973                            pts = CubicIntersect(wt.pts(), wn.pts(), ts);
2974                            break;
2975                        }
2976                        default:
2977                            SkASSERT(0);
2978                    }
2979                    break;
2980                default:
2981                    SkASSERT(0);
2982            }
2983            if (!foundCommonContour && pts > 0) {
2984                test->addCross(next);
2985                next->addCross(test);
2986                foundCommonContour = true;
2987            }
2988            // in addition to recording T values, record matching segment
2989            if (pts == 2 && wn.segmentType() <= Work::kLine_Segment
2990                    && wt.segmentType() <= Work::kLine_Segment) {
2991                wt.addCoincident(wn, ts, swap);
2992                continue;
2993            }
2994            for (int pt = 0; pt < pts; ++pt) {
2995                SkASSERT(ts.fT[0][pt] >= 0 && ts.fT[0][pt] <= 1);
2996                SkASSERT(ts.fT[1][pt] >= 0 && ts.fT[1][pt] <= 1);
2997                int testTAt = wt.addT(ts.fT[swap][pt], wn);
2998                int nextTAt = wn.addT(ts.fT[!swap][pt], wt);
2999                wt.addOtherT(testTAt, ts.fT[!swap][pt], nextTAt);
3000                wn.addOtherT(nextTAt, ts.fT[swap][pt], testTAt);
3001            }
3002        } while (wn.advance());
3003    } while (wt.advance());
3004    return true;
3005}
3006
3007// resolve any coincident pairs found while intersecting, and
3008// see if coincidence is formed by clipping non-concident segments
3009static void coincidenceCheck(SkTDArray<Contour*>& contourList, int winding) {
3010    int contourCount = contourList.count();
3011    for (int cIndex = 0; cIndex < contourCount; ++cIndex) {
3012        Contour* contour = contourList[cIndex];
3013        contour->findTooCloseToCall(winding);
3014    }
3015    for (int cIndex = 0; cIndex < contourCount; ++cIndex) {
3016        Contour* contour = contourList[cIndex];
3017        contour->resolveCoincidence(winding);
3018    }
3019}
3020
3021// project a ray from the top of the contour up and see if it hits anything
3022// note: when we compute line intersections, we keep track of whether
3023// two contours touch, so we need only look at contours not touching this one.
3024// OPTIMIZATION: sort contourList vertically to avoid linear walk
3025static int innerContourCheck(SkTDArray<Contour*>& contourList,
3026        Contour* baseContour, const SkPoint& basePt) {
3027    int contourCount = contourList.count();
3028    SkScalar bestY = SK_ScalarMin;
3029    const Segment* test = NULL;
3030    int tIndex;
3031    double tHit;
3032    for (int cTest = 0; cTest < contourCount; ++cTest) {
3033        Contour* contour = contourList[cTest];
3034        if (basePt.fY < contour->bounds().fTop) {
3035            continue;
3036        }
3037        if (bestY > contour->bounds().fBottom) {
3038            continue;
3039        }
3040        if (baseContour->crosses(contour)) {
3041           continue;
3042        }
3043        const Segment* next = contour->crossedSegment(basePt, bestY, tIndex, tHit);
3044        if (next) {
3045            test = next;
3046        }
3047    }
3048    if (!test) {
3049        baseContour->setWinding(0);
3050        return 0;
3051    }
3052    int winding, windValue;
3053    // If the ray hit the end of a span, we need to construct the wheel of
3054    // angles to find the span closest to the ray -- even if there are just
3055    // two spokes on the wheel.
3056    if (fabs(tHit - test->t(tIndex)) < FLT_EPSILON) {
3057        SkTDArray<Angle> angles;
3058        int end = test->nextSpan(tIndex, 1);
3059        if (end < 0) {
3060            end = test->nextSpan(tIndex, -1);
3061        }
3062        test->addTwoAngles(end, tIndex, angles);
3063        test->buildAngles(tIndex, angles);
3064        SkTDArray<Angle*> sorted;
3065        // OPTIMIZATION: call a sort that, if base point is the leftmost,
3066        // returns the first counterclockwise hour before 6 o'clock,
3067        // or if the base point is rightmost, returns the first clockwise
3068        // hour after 6 o'clock
3069        sortAngles(angles, sorted);
3070#if DEBUG_SORT
3071        sorted[0]->segment()->debugShowSort(sorted, 0, 0, 0);
3072#endif
3073        // walk the sorted angle fan to find the lowest angle
3074        // above the base point. Currently, the first angle in the sorted array
3075        // is 12 noon or an earlier hour (the next counterclockwise)
3076        int count = sorted.count();
3077        int left = -1;
3078        int right = -1;
3079        for (int index = 0; index < count; ++index) {
3080            double indexDx = sorted[index]->dx();
3081            if (indexDx < 0) {
3082                left = index;
3083            } else if (indexDx > 0) {
3084                right = index;
3085                break;
3086            }
3087        }
3088        SkASSERT(left >= 0 || right >= 0);
3089        if (left < 0) {
3090            left = right;
3091        }
3092        const Angle* angle = sorted[left];
3093        test = angle->segment();
3094        winding = test->windSum(angle);
3095        SkASSERT(winding != SK_MinS32);
3096        windValue = test->windValue(angle);
3097    #if 0
3098        if (angle->firstBump(winding)) {
3099            winding -= test->windBump(angle);
3100        }
3101    #endif
3102#if DEBUG_WINDING
3103        SkDebugf("%s angle winding=%d windValue=%d\n", __FUNCTION__, winding,
3104                windValue);
3105#endif
3106    } else {
3107        winding = test->windSum(tIndex);
3108        SkASSERT(winding != SK_MinS32);
3109        windValue = test->windValue(tIndex);
3110#if DEBUG_WINDING
3111        SkDebugf("%s single winding=%d windValue=%d\n", __FUNCTION__, winding,
3112                windValue);
3113#endif
3114    }
3115    // see if a + change in T results in a +/- change in X (compute x'(T))
3116    SkScalar dx = (*SegmentDXAtT[test->verb()])(test->pts(), tHit);
3117#if DEBUG_WINDING
3118    SkDebugf("%s dx=%1.9g\n", __FUNCTION__, dx);
3119#endif
3120    SkASSERT(dx != 0);
3121    if (winding * dx > 0) { // if same signs, result is negative
3122        winding += dx > 0 ? -windValue : windValue;
3123#if DEBUG_WINDING
3124        SkDebugf("%s final winding=%d\n", __FUNCTION__, winding);
3125#endif
3126    }
3127    baseContour->setWinding(winding);
3128    return winding;
3129}
3130
3131// OPTIMIZATION: not crazy about linear search here to find top active y.
3132// seems like we should break down and do the sort, or maybe sort each
3133// contours' segments?
3134// Once the segment array is built, there's no reason I can think of not to
3135// sort it in Y. hmmm
3136// FIXME: return the contour found to pass to inner contour check
3137static Segment* findTopContour(SkTDArray<Contour*>& contourList,
3138        Contour*& topContour) {
3139    int contourCount = contourList.count();
3140    int cIndex = 0;
3141    Segment* topStart;
3142    SkScalar bestY = SK_ScalarMax;
3143    Contour* contour;
3144    do {
3145        contour = contourList[cIndex];
3146        topStart = contour->topSegment(bestY);
3147    } while (!topStart && ++cIndex < contourCount);
3148    if (!topStart) {
3149        return NULL;
3150    }
3151    topContour = contour;
3152    while (++cIndex < contourCount) {
3153        contour = contourList[cIndex];
3154        if (bestY < contour->bounds().fTop) {
3155            continue;
3156        }
3157        SkScalar testY = SK_ScalarMax;
3158        Segment* test = contour->topSegment(testY);
3159        if (!test || bestY <= testY) {
3160            continue;
3161        }
3162        topContour = contour;
3163        topStart = test;
3164        bestY = testY;
3165    }
3166    return topStart;
3167}
3168
3169static Segment* findChase(SkTDArray<Span*>& chase, int& tIndex, int& endIndex,
3170        int contourWinding) {
3171    while (chase.count()) {
3172        Span* span = chase[chase.count() - 1];
3173        const Span& backPtr = span->fOther->span(span->fOtherIndex);
3174        Segment* segment = backPtr.fOther;
3175        tIndex = backPtr.fOtherIndex;
3176        SkTDArray<Angle> angles;
3177        int done = 0;
3178        if (segment->activeAngle(tIndex, done, angles)) {
3179            Angle* last = angles.end() - 1;
3180            tIndex = last->start();
3181            endIndex = last->end();
3182            return last->segment();
3183        }
3184        if (done == angles.count()) {
3185            chase.pop(&span);
3186            continue;
3187        }
3188        SkTDArray<Angle*> sorted;
3189        sortAngles(angles, sorted);
3190        // find first angle, initialize winding to computed fWindSum
3191        int firstIndex = -1;
3192        const Angle* angle;
3193        int spanWinding;
3194        do {
3195            angle = sorted[++firstIndex];
3196            spanWinding = angle->segment()->windSum(angle);
3197        } while (spanWinding == SK_MinS32);
3198    #if DEBUG_SORT
3199        angle->segment()->debugShowSort(sorted, firstIndex, contourWinding,
3200                spanWinding);
3201    #endif
3202        if (angle->firstBump(spanWinding)) {
3203            spanWinding -= angle->segment()->windBump(angle);
3204        }
3205        // we care about first sign and whether wind sum indicates this
3206        // edge is inside or outside. Maybe need to pass span winding
3207        // or first winding or something into this function?
3208        // advance to first undone angle, then return it and winding
3209        // (to set whether edges are active or not)
3210        int nextIndex = firstIndex + 1;
3211        int angleCount = sorted.count();
3212        int lastIndex = firstIndex != 0 ? firstIndex : angleCount;
3213        do {
3214            SkASSERT(nextIndex != firstIndex);
3215            if (nextIndex == angleCount) {
3216                nextIndex = 0;
3217            }
3218            const Angle* angle = sorted[nextIndex];
3219            segment = angle->segment();
3220            int maxWinding = spanWinding;
3221            spanWinding -= segment->windBump(angle);
3222            if (maxWinding * spanWinding < 0) {
3223                SkDebugf("%s flipped sign %d %d\n", __FUNCTION__, maxWinding, spanWinding);
3224            }
3225            tIndex = angle->start();
3226            endIndex = angle->end();
3227            int lesser = SkMin32(tIndex, endIndex);
3228            const Span& nextSpan = segment->span(lesser);
3229            if (!nextSpan.fDone) {
3230            // FIXME: this be wrong. assign startWinding if edge is in
3231            // same direction. If the direction is opposite, winding to
3232            // assign is flipped sign or +/- 1?
3233                if (abs(maxWinding) < abs(spanWinding)) {
3234                    maxWinding = spanWinding;
3235                }
3236                segment->markWinding(lesser, maxWinding);
3237                break;
3238            }
3239        } while (++nextIndex != lastIndex);
3240        return segment;
3241    }
3242    return NULL;
3243}
3244
3245#if DEBUG_ACTIVE_SPANS
3246static void debugShowActiveSpans(SkTDArray<Contour*>& contourList) {
3247    for (int index = 0; index < contourList.count(); ++ index) {
3248        contourList[index]->debugShowActiveSpans();
3249    }
3250}
3251#endif
3252
3253// Each segment may have an inside or an outside. Segments contained within
3254// winding may have insides on either side, and form a contour that should be
3255// ignored. Segments that are coincident with opposing direction segments may
3256// have outsides on either side, and should also disappear.
3257// 'Normal' segments will have one inside and one outside. Subsequent connections
3258// when winding should follow the intersection direction. If more than one edge
3259// is an option, choose first edge that continues the inside.
3260    // since we start with leftmost top edge, we'll traverse through a
3261    // smaller angle counterclockwise to get to the next edge.
3262static void bridge(SkTDArray<Contour*>& contourList, SkPath& simple) {
3263    bool firstContour = true;
3264    do {
3265        Contour* topContour;
3266        Segment* topStart = findTopContour(contourList, topContour);
3267        if (!topStart) {
3268            break;
3269        }
3270        // Start at the top. Above the top is outside, below is inside.
3271        // follow edges to intersection by changing the index by direction.
3272        int index, endIndex;
3273        Segment* current = topStart->findTop(index, endIndex);
3274        int contourWinding;
3275        if (firstContour) {
3276            contourWinding = 0;
3277            firstContour = false;
3278        } else {
3279            const SkPoint& topPoint = current->xyAtT(endIndex);
3280            contourWinding = innerContourCheck(contourList, topContour, topPoint);
3281#if DEBUG_WINDING
3282            SkDebugf("%s contourWinding=%d\n", __FUNCTION__, contourWinding);
3283#endif
3284        }
3285        SkPoint lastPt;
3286        bool firstTime = true;
3287        int winding = contourWinding;
3288        int spanWinding = current->spanSign(index, endIndex);
3289     //   int firstWinding = contourWinding + spanWinding;
3290        // FIXME: needs work. While it works in limited situations, it does
3291        // not always compute winding correctly. Active should be removed and instead
3292        // the initial winding should be correctly passed in so that if the
3293        // inner contour is wound the same way, it never finds an accumulated
3294        // winding of zero. Inside 'find next', we need to look for transitions
3295        // other than zero when resolving sorted angles.
3296        SkTDArray<Span*> chaseArray;
3297        do {
3298            bool active = winding * spanWinding <= 0
3299                    && abs(winding) <= abs(spanWinding);
3300        #if DEBUG_WINDING
3301            if (abs(winding) > abs(spanWinding) && winding * spanWinding < 0) {
3302                SkDebugf("%s *** unexpected active?\n", __FUNCTION__);
3303            }
3304            SkDebugf("%s active=%s winding=%d spanWinding=%d\n",
3305                    __FUNCTION__, active ? "true" : "false",
3306                    winding, spanWinding);
3307        #endif
3308            const SkPoint* firstPt = NULL;
3309            do {
3310                SkASSERT(!current->done());
3311                int nextStart, nextEnd;
3312                Segment* next = current->findNext(chaseArray, winding,
3313                        contourWinding, firstTime, active, index, endIndex,
3314                        nextStart, nextEnd, spanWinding);
3315                if (!next) {
3316                    break;
3317                }
3318                if (!firstPt) {
3319                    firstPt = &current->addMoveTo(index, simple, active);
3320                }
3321                lastPt = current->addCurveTo(index, endIndex, simple, active);
3322                current = next;
3323                index = nextStart;
3324                endIndex = nextEnd;
3325                firstTime = false;
3326            } while (*firstPt != lastPt && (active || !current->done()));
3327            if (firstPt && active) {
3328        #if DEBUG_PATH_CONSTRUCTION
3329                SkDebugf("%s close\n", __FUNCTION__);
3330        #endif
3331                simple.close();
3332            }
3333            current = findChase(chaseArray, index, endIndex, contourWinding);
3334        #if DEBUG_ACTIVE_SPANS
3335            debugShowActiveSpans(contourList);
3336        #endif
3337            if (!current) {
3338                break;
3339            }
3340            int lesser = SkMin32(index, endIndex);
3341            spanWinding = current->windSum(lesser);
3342            int spanValue = current->windValue(lesser);
3343            SkASSERT(spanWinding != SK_MinS32);
3344            int spanSign = current->spanSign(index, endIndex);
3345        #if DEBUG_WINDING
3346            SkDebugf("%s spanWinding=%d spanSign=%d winding=%d spanValue=%d\n",
3347                    __FUNCTION__, spanWinding, spanSign, winding, spanValue);
3348        #endif
3349            if (spanWinding * spanSign < 0) {
3350        #if DEBUG_WINDING
3351                SkDebugf("%s spanWinding * spanSign < 0\n", __FUNCTION__);
3352        #endif
3353   //             SkTSwap<int>(index, endIndex);
3354            }
3355            if (abs(spanWinding) > spanValue) {
3356                winding = spanWinding;
3357                spanWinding = spanValue * SkSign32(spanWinding);
3358                winding -= spanWinding;
3359        #if DEBUG_WINDING
3360                SkDebugf("%s spanWinding=%d winding=%d\n", __FUNCTION__,
3361                        spanWinding, winding);
3362        #endif
3363            } else {
3364        #if DEBUG_WINDING
3365                SkDebugf("%s ->0 contourWinding=%d winding=%d\n", __FUNCTION__,
3366                        contourWinding, winding);
3367        #endif
3368                winding = 0;
3369            }
3370        } while (true);
3371    } while (true);
3372}
3373
3374static void fixOtherTIndex(SkTDArray<Contour*>& contourList) {
3375    int contourCount = contourList.count();
3376    for (int cTest = 0; cTest < contourCount; ++cTest) {
3377        Contour* contour = contourList[cTest];
3378        contour->fixOtherTIndex();
3379    }
3380}
3381
3382static void makeContourList(SkTArray<Contour>& contours,
3383        SkTDArray<Contour*>& list) {
3384    int count = contours.count();
3385    if (count == 0) {
3386        return;
3387    }
3388    for (int index = 0; index < count; ++index) {
3389        *list.append() = &contours[index];
3390    }
3391    QSort<Contour>(list.begin(), list.end() - 1);
3392}
3393
3394void simplifyx(const SkPath& path, SkPath& simple) {
3395    // returns 1 for evenodd, -1 for winding, regardless of inverse-ness
3396    int winding = (path.getFillType() & 1) ? 1 : -1;
3397    simple.reset();
3398    simple.setFillType(SkPath::kEvenOdd_FillType);
3399
3400    // turn path into list of segments
3401    SkTArray<Contour> contours;
3402    // FIXME: add self-intersecting cubics' T values to segment
3403    EdgeBuilder builder(path, contours);
3404    SkTDArray<Contour*> contourList;
3405    makeContourList(contours, contourList);
3406    Contour** currentPtr = contourList.begin();
3407    if (!currentPtr) {
3408        return;
3409    }
3410    Contour** listEnd = contourList.end();
3411    // find all intersections between segments
3412    do {
3413        Contour** nextPtr = currentPtr;
3414        Contour* current = *currentPtr++;
3415        Contour* next;
3416        do {
3417            next = *nextPtr++;
3418        } while (addIntersectTs(current, next) && nextPtr != listEnd);
3419    } while (currentPtr != listEnd);
3420    // eat through coincident edges
3421    coincidenceCheck(contourList, winding);
3422    fixOtherTIndex(contourList);
3423    // construct closed contours
3424    bridge(contourList, simple);
3425}
3426
3427