SkDQuadLineIntersection.cpp revision 4fdbb229649caf74e5c1b55a1823926df903af34
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
89
90class LineQuadraticIntersections {
91public:
92    enum PinTPoint {
93        kPointUninitialized,
94        kPointInitialized
95    };
96
97    LineQuadraticIntersections(const SkDQuad& q, const SkDLine& l, SkIntersections* i)
98        : fQuad(q)
99        , fLine(l)
100        , fIntersections(i)
101        , fAllowNear(true) {
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        double rootVals[2];
141        int roots = intersectRay(rootVals);
142        for (int index = 0; index < roots; ++index) {
143            double quadT = rootVals[index];
144            double lineT = findLineT(quadT);
145            SkDPoint pt;
146            if (pinTs(&quadT, &lineT, &pt, kPointUninitialized)) {
147                fIntersections->insert(quadT, lineT, pt);
148            }
149        }
150        if (fAllowNear) {
151            addNearEndPoints();
152        }
153        return fIntersections->used();
154    }
155
156    int horizontalIntersect(double axisIntercept, double roots[2]) {
157        double D = fQuad[2].fY;  // f
158        double E = fQuad[1].fY;  // e
159        double F = fQuad[0].fY;  // d
160        D += F - 2 * E;         // D = d - 2*e + f
161        E -= F;                 // E = -(d - e)
162        F -= axisIntercept;
163        return SkDQuad::RootsValidT(D, 2 * E, F, roots);
164    }
165
166    int horizontalIntersect(double axisIntercept, double left, double right, bool flipped) {
167        addExactHorizontalEndPoints(left, right, axisIntercept);
168        double rootVals[2];
169        int roots = horizontalIntersect(axisIntercept, rootVals);
170        for (int index = 0; index < roots; ++index) {
171            double quadT = rootVals[index];
172            SkDPoint pt = fQuad.ptAtT(quadT);
173            double lineT = (pt.fX - left) / (right - left);
174            if (pinTs(&quadT, &lineT, &pt, kPointInitialized)) {
175                fIntersections->insert(quadT, lineT, pt);
176            }
177        }
178        if (fAllowNear) {
179            addNearHorizontalEndPoints(left, right, axisIntercept);
180        }
181        if (flipped) {
182            fIntersections->flip();
183        }
184        return fIntersections->used();
185    }
186
187    int verticalIntersect(double axisIntercept, double roots[2]) {
188        double D = fQuad[2].fX;  // f
189        double E = fQuad[1].fX;  // e
190        double F = fQuad[0].fX;  // d
191        D += F - 2 * E;         // D = d - 2*e + f
192        E -= F;                 // E = -(d - e)
193        F -= axisIntercept;
194        return SkDQuad::RootsValidT(D, 2 * E, F, roots);
195    }
196
197    int verticalIntersect(double axisIntercept, double top, double bottom, bool flipped) {
198        addExactVerticalEndPoints(top, bottom, axisIntercept);
199        double rootVals[2];
200        int roots = verticalIntersect(axisIntercept, rootVals);
201        for (int index = 0; index < roots; ++index) {
202            double quadT = rootVals[index];
203            SkDPoint pt = fQuad.ptAtT(quadT);
204            double lineT = (pt.fY - top) / (bottom - top);
205            if (pinTs(&quadT, &lineT, &pt, kPointInitialized)) {
206                fIntersections->insert(quadT, lineT, pt);
207            }
208        }
209        if (fAllowNear) {
210            addNearVerticalEndPoints(top, bottom, axisIntercept);
211        }
212        if (flipped) {
213            fIntersections->flip();
214        }
215        return fIntersections->used();
216    }
217
218protected:
219    // add endpoints first to get zero and one t values exactly
220    void addExactEndPoints() {
221        for (int qIndex = 0; qIndex < 3; qIndex += 2) {
222            double lineT = fLine.exactPoint(fQuad[qIndex]);
223            if (lineT < 0) {
224                continue;
225            }
226            double quadT = (double) (qIndex >> 1);
227            fIntersections->insert(quadT, lineT, fQuad[qIndex]);
228        }
229    }
230
231    void addNearEndPoints() {
232        for (int qIndex = 0; qIndex < 3; qIndex += 2) {
233            double quadT = (double) (qIndex >> 1);
234            if (fIntersections->hasT(quadT)) {
235                continue;
236            }
237            double lineT = fLine.nearPoint(fQuad[qIndex]);
238            if (lineT < 0) {
239                continue;
240            }
241            fIntersections->insert(quadT, lineT, fQuad[qIndex]);
242        }
243        // FIXME: see if line end is nearly on quad
244    }
245
246    void addExactHorizontalEndPoints(double left, double right, double y) {
247        for (int qIndex = 0; qIndex < 3; qIndex += 2) {
248            double lineT = SkDLine::ExactPointH(fQuad[qIndex], left, right, y);
249            if (lineT < 0) {
250                continue;
251            }
252            double quadT = (double) (qIndex >> 1);
253            fIntersections->insert(quadT, lineT, fQuad[qIndex]);
254        }
255    }
256
257    void addNearHorizontalEndPoints(double left, double right, double y) {
258        for (int qIndex = 0; qIndex < 3; qIndex += 2) {
259            double quadT = (double) (qIndex >> 1);
260            if (fIntersections->hasT(quadT)) {
261                continue;
262            }
263            double lineT = SkDLine::NearPointH(fQuad[qIndex], left, right, y);
264            if (lineT < 0) {
265                continue;
266            }
267            fIntersections->insert(quadT, lineT, fQuad[qIndex]);
268        }
269        // FIXME: see if line end is nearly on quad
270    }
271
272    void addExactVerticalEndPoints(double top, double bottom, double x) {
273        for (int qIndex = 0; qIndex < 3; qIndex += 2) {
274            double lineT = SkDLine::ExactPointV(fQuad[qIndex], top, bottom, x);
275            if (lineT < 0) {
276                continue;
277            }
278            double quadT = (double) (qIndex >> 1);
279            fIntersections->insert(quadT, lineT, fQuad[qIndex]);
280        }
281    }
282
283    void addNearVerticalEndPoints(double top, double bottom, double x) {
284        for (int qIndex = 0; qIndex < 3; qIndex += 2) {
285            double quadT = (double) (qIndex >> 1);
286            if (fIntersections->hasT(quadT)) {
287                continue;
288            }
289            double lineT = SkDLine::NearPointV(fQuad[qIndex], top, bottom, x);
290            if (lineT < 0) {
291                continue;
292            }
293            fIntersections->insert(quadT, lineT, fQuad[qIndex]);
294        }
295        // FIXME: see if line end is nearly on quad
296    }
297
298    double findLineT(double t) {
299        SkDPoint xy = fQuad.ptAtT(t);
300        double dx = fLine[1].fX - fLine[0].fX;
301        double dy = fLine[1].fY - fLine[0].fY;
302        double dxT = (xy.fX - fLine[0].fX) / dx;
303        double dyT = (xy.fY - fLine[0].fY) / dy;
304        if (!between(FLT_EPSILON, dxT, 1 - FLT_EPSILON) && between(0, dyT, 1)) {
305            return dyT;
306        }
307        if (!between(FLT_EPSILON, dyT, 1 - FLT_EPSILON) && between(0, dxT, 1)) {
308            return dxT;
309        }
310        return fabs(dx) > fabs(dy) ? dxT : dyT;
311    }
312
313    bool pinTs(double* quadT, double* lineT, SkDPoint* pt, PinTPoint ptSet) {
314        if (!approximately_one_or_less(*lineT)) {
315            return false;
316        }
317        if (!approximately_zero_or_more(*lineT)) {
318            return false;
319        }
320        double qT = *quadT = SkPinT(*quadT);
321        double lT = *lineT = SkPinT(*lineT);
322        if (lT == 0 || lT == 1 || (ptSet == kPointUninitialized && qT != 0 && qT != 1)) {
323            *pt = fLine.ptAtT(lT);
324        } else if (ptSet == kPointUninitialized) {
325            *pt = fQuad.ptAtT(qT);
326        }
327        return true;
328    }
329
330private:
331    const SkDQuad& fQuad;
332    const SkDLine& fLine;
333    SkIntersections* fIntersections;
334    bool fAllowNear;
335};
336
337// utility for pairs of coincident quads
338static double horizontalIntersect(const SkDQuad& quad, const SkDPoint& pt) {
339    LineQuadraticIntersections q(quad, *(static_cast<SkDLine*>(0)),
340            static_cast<SkIntersections*>(0));
341    double rootVals[2];
342    int roots = q.horizontalIntersect(pt.fY, rootVals);
343    for (int index = 0; index < roots; ++index) {
344        double t = rootVals[index];
345        SkDPoint qPt = quad.ptAtT(t);
346        if (AlmostEqualUlps(qPt.fX, pt.fX)) {
347            return t;
348        }
349    }
350    return -1;
351}
352
353static double verticalIntersect(const SkDQuad& quad, const SkDPoint& pt) {
354    LineQuadraticIntersections q(quad, *(static_cast<SkDLine*>(0)),
355            static_cast<SkIntersections*>(0));
356    double rootVals[2];
357    int roots = q.verticalIntersect(pt.fX, rootVals);
358    for (int index = 0; index < roots; ++index) {
359        double t = rootVals[index];
360        SkDPoint qPt = quad.ptAtT(t);
361        if (AlmostEqualUlps(qPt.fY, pt.fY)) {
362            return t;
363        }
364    }
365    return -1;
366}
367
368double SkIntersections::Axial(const SkDQuad& q1, const SkDPoint& p, bool vertical) {
369    if (vertical) {
370        return verticalIntersect(q1, p);
371    }
372    return horizontalIntersect(q1, p);
373}
374
375int SkIntersections::horizontal(const SkDQuad& quad, double left, double right, double y,
376                                bool flipped) {
377    SkDLine line = {{{ left, y }, { right, y }}};
378    LineQuadraticIntersections q(quad, line, this);
379    return q.horizontalIntersect(y, left, right, flipped);
380}
381
382int SkIntersections::vertical(const SkDQuad& quad, double top, double bottom, double x,
383                              bool flipped) {
384    SkDLine line = {{{ x, top }, { x, bottom }}};
385    LineQuadraticIntersections q(quad, line, this);
386    return q.verticalIntersect(x, top, bottom, flipped);
387}
388
389int SkIntersections::intersect(const SkDQuad& quad, const SkDLine& line) {
390    LineQuadraticIntersections q(quad, line, this);
391    q.allowNear(fAllowNear);
392    return q.intersect();
393}
394
395int SkIntersections::intersectRay(const SkDQuad& quad, const SkDLine& line) {
396    LineQuadraticIntersections q(quad, line, this);
397    fUsed = q.intersectRay(fT[0]);
398    for (int index = 0; index < fUsed; ++index) {
399        fPt[index] = quad.ptAtT(fT[0][index]);
400    }
401    return fUsed;
402}
403