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 "SkIntersections.h"
8#include "SkPathOpsLine.h"
9#include "SkPathOpsQuad.h"
10
11/*
12Find the interection of a line and quadratic by solving for valid t values.
13
14From http://stackoverflow.com/questions/1853637/how-to-find-the-mathematical-function-defining-a-bezier-curve
15
16"A Bezier curve is a parametric function. A quadratic Bezier curve (i.e. three
17control points) can be expressed as: F(t) = A(1 - t)^2 + B(1 - t)t + Ct^2 where
18A, B and C are points and t goes from zero to one.
19
20This will give you two equations:
21
22  x = a(1 - t)^2 + b(1 - t)t + ct^2
23  y = d(1 - t)^2 + e(1 - t)t + ft^2
24
25If you add for instance the line equation (y = kx + m) to that, you'll end up
26with three equations and three unknowns (x, y and t)."
27
28Similar to above, the quadratic is represented as
29  x = a(1-t)^2 + 2b(1-t)t + ct^2
30  y = d(1-t)^2 + 2e(1-t)t + ft^2
31and the line as
32  y = g*x + h
33
34Using Mathematica, solve for the values of t where the quadratic intersects the
35line:
36
37  (in)  t1 = Resultant[a*(1 - t)^2 + 2*b*(1 - t)*t + c*t^2 - x,
38                       d*(1 - t)^2 + 2*e*(1 - t)*t  + f*t^2 - g*x - h, x]
39  (out) -d + h + 2 d t - 2 e t - d t^2 + 2 e t^2 - f t^2 +
40         g  (a - 2 a t + 2 b t + a t^2 - 2 b t^2 + c t^2)
41  (in)  Solve[t1 == 0, t]
42  (out) {
43    {t -> (-2 d + 2 e +   2 a g - 2 b g    -
44      Sqrt[(2 d - 2 e -   2 a g + 2 b g)^2 -
45          4 (-d + 2 e - f + a g - 2 b g    + c g) (-d + a g + h)]) /
46         (2 (-d + 2 e - f + a g - 2 b g    + c g))
47         },
48    {t -> (-2 d + 2 e +   2 a g - 2 b g    +
49      Sqrt[(2 d - 2 e -   2 a g + 2 b g)^2 -
50          4 (-d + 2 e - f + a g - 2 b g    + c g) (-d + a g + h)]) /
51         (2 (-d + 2 e - f + a g - 2 b g    + c g))
52         }
53        }
54
55Using the results above (when the line tends towards horizontal)
56       A =   (-(d - 2*e + f) + g*(a - 2*b + c)     )
57       B = 2*( (d -   e    ) - g*(a -   b    )     )
58       C =   (-(d          ) + g*(a          ) + h )
59
60If g goes to infinity, we can rewrite the line in terms of x.
61  x = g'*y + h'
62
63And solve accordingly in Mathematica:
64
65  (in)  t2 = Resultant[a*(1 - t)^2 + 2*b*(1 - t)*t + c*t^2 - g'*y - h',
66                       d*(1 - t)^2 + 2*e*(1 - t)*t  + f*t^2 - y, y]
67  (out)  a - h' - 2 a t + 2 b t + a t^2 - 2 b t^2 + c t^2 -
68         g'  (d - 2 d t + 2 e t + d t^2 - 2 e t^2 + f t^2)
69  (in)  Solve[t2 == 0, t]
70  (out) {
71    {t -> (2 a - 2 b -   2 d g' + 2 e g'    -
72    Sqrt[(-2 a + 2 b +   2 d g' - 2 e g')^2 -
73          4 (a - 2 b + c - d g' + 2 e g' - f g') (a - d g' - h')]) /
74         (2 (a - 2 b + c - d g' + 2 e g' - f g'))
75         },
76    {t -> (2 a - 2 b -   2 d g' + 2 e g'    +
77    Sqrt[(-2 a + 2 b +   2 d g' - 2 e g')^2 -
78          4 (a - 2 b + c - d g' + 2 e g' - f g') (a - d g' - h')])/
79         (2 (a - 2 b + c - d g' + 2 e g' - f g'))
80         }
81        }
82
83Thus, if the slope of the line tends towards vertical, we use:
84       A =   ( (a - 2*b + c) - g'*(d  - 2*e + f)      )
85       B = 2*(-(a -   b    ) + g'*(d  -   e    )      )
86       C =   ( (a          ) - g'*(d           ) - h' )
87 */
88
89class LineQuadraticIntersections {
90public:
91    enum PinTPoint {
92        kPointUninitialized,
93        kPointInitialized
94    };
95
96    LineQuadraticIntersections(const SkDQuad& q, const SkDLine& l, SkIntersections* i)
97        : fQuad(q)
98        , fLine(l)
99        , fIntersections(i)
100        , fAllowNear(true) {
101        i->setMax(3);  // allow short partial coincidence plus discrete intersection
102    }
103
104    void allowNear(bool allow) {
105        fAllowNear = allow;
106    }
107
108    int intersectRay(double roots[2]) {
109    /*
110        solve by rotating line+quad so line is horizontal, then finding the roots
111        set up matrix to rotate quad to x-axis
112        |cos(a) -sin(a)|
113        |sin(a)  cos(a)|
114        note that cos(a) = A(djacent) / Hypoteneuse
115                  sin(a) = O(pposite) / Hypoteneuse
116        since we are computing Ts, we can ignore hypoteneuse, the scale factor:
117        |  A     -O    |
118        |  O      A    |
119        A = line[1].fX - line[0].fX (adjacent side of the right triangle)
120        O = line[1].fY - line[0].fY (opposite side of the right triangle)
121        for each of the three points (e.g. n = 0 to 2)
122        quad[n].fY' = (quad[n].fY - line[0].fY) * A - (quad[n].fX - line[0].fX) * O
123    */
124        double adj = fLine[1].fX - fLine[0].fX;
125        double opp = fLine[1].fY - fLine[0].fY;
126        double r[3];
127        for (int n = 0; n < 3; ++n) {
128            r[n] = (fQuad[n].fY - fLine[0].fY) * adj - (fQuad[n].fX - fLine[0].fX) * opp;
129        }
130        double A = r[2];
131        double B = r[1];
132        double C = r[0];
133        A += C - 2 * B;  // A = a - 2*b + c
134        B -= C;  // B = -(b - c)
135        return SkDQuad::RootsValidT(A, 2 * B, C, roots);
136    }
137
138    int intersect() {
139        addExactEndPoints();
140        if (fAllowNear) {
141            addNearEndPoints();
142        }
143        if (fIntersections->used() == 2) {
144            // FIXME : need sharable code that turns spans into coincident if middle point is on
145        } else {
146            double rootVals[2];
147            int roots = intersectRay(rootVals);
148            for (int index = 0; index < roots; ++index) {
149                double quadT = rootVals[index];
150                double lineT = findLineT(quadT);
151                SkDPoint pt;
152                if (pinTs(&quadT, &lineT, &pt, kPointUninitialized)) {
153                    fIntersections->insert(quadT, lineT, pt);
154                }
155            }
156        }
157        return fIntersections->used();
158    }
159
160    int horizontalIntersect(double axisIntercept, double roots[2]) {
161        double D = fQuad[2].fY;  // f
162        double E = fQuad[1].fY;  // e
163        double F = fQuad[0].fY;  // d
164        D += F - 2 * E;         // D = d - 2*e + f
165        E -= F;                 // E = -(d - e)
166        F -= axisIntercept;
167        return SkDQuad::RootsValidT(D, 2 * E, F, roots);
168    }
169
170    int horizontalIntersect(double axisIntercept, double left, double right, bool flipped) {
171        addExactHorizontalEndPoints(left, right, axisIntercept);
172        if (fAllowNear) {
173            addNearHorizontalEndPoints(left, right, axisIntercept);
174        }
175        double rootVals[2];
176        int roots = horizontalIntersect(axisIntercept, rootVals);
177        for (int index = 0; index < roots; ++index) {
178            double quadT = rootVals[index];
179            SkDPoint pt = fQuad.ptAtT(quadT);
180            double lineT = (pt.fX - left) / (right - left);
181            if (pinTs(&quadT, &lineT, &pt, kPointInitialized)) {
182                fIntersections->insert(quadT, lineT, pt);
183            }
184        }
185        if (flipped) {
186            fIntersections->flip();
187        }
188        return fIntersections->used();
189    }
190
191    int verticalIntersect(double axisIntercept, double roots[2]) {
192        double D = fQuad[2].fX;  // f
193        double E = fQuad[1].fX;  // e
194        double F = fQuad[0].fX;  // d
195        D += F - 2 * E;         // D = d - 2*e + f
196        E -= F;                 // E = -(d - e)
197        F -= axisIntercept;
198        return SkDQuad::RootsValidT(D, 2 * E, F, roots);
199    }
200
201    int verticalIntersect(double axisIntercept, double top, double bottom, bool flipped) {
202        addExactVerticalEndPoints(top, bottom, axisIntercept);
203        if (fAllowNear) {
204            addNearVerticalEndPoints(top, bottom, axisIntercept);
205        }
206        double rootVals[2];
207        int roots = verticalIntersect(axisIntercept, rootVals);
208        for (int index = 0; index < roots; ++index) {
209            double quadT = rootVals[index];
210            SkDPoint pt = fQuad.ptAtT(quadT);
211            double lineT = (pt.fY - top) / (bottom - top);
212            if (pinTs(&quadT, &lineT, &pt, kPointInitialized)) {
213                fIntersections->insert(quadT, lineT, pt);
214            }
215        }
216        if (flipped) {
217            fIntersections->flip();
218        }
219        return fIntersections->used();
220    }
221
222protected:
223    // add endpoints first to get zero and one t values exactly
224    void addExactEndPoints() {
225        for (int qIndex = 0; qIndex < 3; qIndex += 2) {
226            double lineT = fLine.exactPoint(fQuad[qIndex]);
227            if (lineT < 0) {
228                continue;
229            }
230            double quadT = (double) (qIndex >> 1);
231            fIntersections->insert(quadT, lineT, fQuad[qIndex]);
232        }
233    }
234
235    void addNearEndPoints() {
236        for (int qIndex = 0; qIndex < 3; qIndex += 2) {
237            double quadT = (double) (qIndex >> 1);
238            if (fIntersections->hasT(quadT)) {
239                continue;
240            }
241            double lineT = fLine.nearPoint(fQuad[qIndex], NULL);
242            if (lineT < 0) {
243                continue;
244            }
245            fIntersections->insert(quadT, lineT, fQuad[qIndex]);
246        }
247        // FIXME: see if line end is nearly on quad
248    }
249
250    void addExactHorizontalEndPoints(double left, double right, double y) {
251        for (int qIndex = 0; qIndex < 3; qIndex += 2) {
252            double lineT = SkDLine::ExactPointH(fQuad[qIndex], left, right, y);
253            if (lineT < 0) {
254                continue;
255            }
256            double quadT = (double) (qIndex >> 1);
257            fIntersections->insert(quadT, lineT, fQuad[qIndex]);
258        }
259    }
260
261    void addNearHorizontalEndPoints(double left, double right, double y) {
262        for (int qIndex = 0; qIndex < 3; qIndex += 2) {
263            double quadT = (double) (qIndex >> 1);
264            if (fIntersections->hasT(quadT)) {
265                continue;
266            }
267            double lineT = SkDLine::NearPointH(fQuad[qIndex], left, right, y);
268            if (lineT < 0) {
269                continue;
270            }
271            fIntersections->insert(quadT, lineT, fQuad[qIndex]);
272        }
273        // FIXME: see if line end is nearly on quad
274    }
275
276    void addExactVerticalEndPoints(double top, double bottom, double x) {
277        for (int qIndex = 0; qIndex < 3; qIndex += 2) {
278            double lineT = SkDLine::ExactPointV(fQuad[qIndex], top, bottom, x);
279            if (lineT < 0) {
280                continue;
281            }
282            double quadT = (double) (qIndex >> 1);
283            fIntersections->insert(quadT, lineT, fQuad[qIndex]);
284        }
285    }
286
287    void addNearVerticalEndPoints(double top, double bottom, double x) {
288        for (int qIndex = 0; qIndex < 3; qIndex += 2) {
289            double quadT = (double) (qIndex >> 1);
290            if (fIntersections->hasT(quadT)) {
291                continue;
292            }
293            double lineT = SkDLine::NearPointV(fQuad[qIndex], top, bottom, x);
294            if (lineT < 0) {
295                continue;
296            }
297            fIntersections->insert(quadT, lineT, fQuad[qIndex]);
298        }
299        // FIXME: see if line end is nearly on quad
300    }
301
302    double findLineT(double t) {
303        SkDPoint xy = fQuad.ptAtT(t);
304        double dx = fLine[1].fX - fLine[0].fX;
305        double dy = fLine[1].fY - fLine[0].fY;
306        if (fabs(dx) > fabs(dy)) {
307            return (xy.fX - fLine[0].fX) / dx;
308        }
309        return (xy.fY - fLine[0].fY) / dy;
310    }
311
312    bool pinTs(double* quadT, double* lineT, SkDPoint* pt, PinTPoint ptSet) {
313        if (!approximately_one_or_less_double(*lineT)) {
314            return false;
315        }
316        if (!approximately_zero_or_more_double(*lineT)) {
317            return false;
318        }
319        double qT = *quadT = SkPinT(*quadT);
320        double lT = *lineT = SkPinT(*lineT);
321        if (lT == 0 || lT == 1 || (ptSet == kPointUninitialized && qT != 0 && qT != 1)) {
322            *pt = fLine.ptAtT(lT);
323        } else if (ptSet == kPointUninitialized) {
324            *pt = fQuad.ptAtT(qT);
325        }
326        SkPoint gridPt = pt->asSkPoint();
327        if (SkDPoint::ApproximatelyEqual(gridPt, fLine[0].asSkPoint())) {
328            *pt = fLine[0];
329            *lineT = 0;
330        } else if (SkDPoint::ApproximatelyEqual(gridPt, fLine[1].asSkPoint())) {
331            *pt = fLine[1];
332            *lineT = 1;
333        }
334        if (fIntersections->used() > 0 && approximately_equal((*fIntersections)[1][0], *lineT)) {
335            return false;
336        }
337        if (gridPt == fQuad[0].asSkPoint()) {
338            *pt = fQuad[0];
339            *quadT = 0;
340        } else if (gridPt == fQuad[2].asSkPoint()) {
341            *pt = fQuad[2];
342            *quadT = 1;
343        }
344        return true;
345    }
346
347private:
348    const SkDQuad& fQuad;
349    const SkDLine& fLine;
350    SkIntersections* fIntersections;
351    bool fAllowNear;
352};
353
354int SkIntersections::horizontal(const SkDQuad& quad, double left, double right, double y,
355                                bool flipped) {
356    SkDLine line = {{{ left, y }, { right, y }}};
357    LineQuadraticIntersections q(quad, line, this);
358    return q.horizontalIntersect(y, left, right, flipped);
359}
360
361int SkIntersections::vertical(const SkDQuad& quad, double top, double bottom, double x,
362                              bool flipped) {
363    SkDLine line = {{{ x, top }, { x, bottom }}};
364    LineQuadraticIntersections q(quad, line, this);
365    return q.verticalIntersect(x, top, bottom, flipped);
366}
367
368int SkIntersections::intersect(const SkDQuad& quad, const SkDLine& line) {
369    LineQuadraticIntersections q(quad, line, this);
370    q.allowNear(fAllowNear);
371    return q.intersect();
372}
373
374int SkIntersections::intersectRay(const SkDQuad& quad, const SkDLine& line) {
375    LineQuadraticIntersections q(quad, line, this);
376    fUsed = q.intersectRay(fT[0]);
377    for (int index = 0; index < fUsed; ++index) {
378        fPt[index] = quad.ptAtT(fT[0][index]);
379    }
380    return fUsed;
381}
382