1/****************************************************************************
2**
3** Copyright (C) 2016 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the QtGui module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** GNU Lesser General Public License Usage
18** Alternatively, this file may be used under the terms of the GNU Lesser
19** General Public License version 3 as published by the Free Software
20** Foundation and appearing in the file LICENSE.LGPL3 included in the
21** packaging of this file. Please review the following information to
22** ensure the GNU Lesser General Public License version 3 requirements
23** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24**
25** GNU General Public License Usage
26** Alternatively, this file may be used under the terms of the GNU
27** General Public License version 2.0 or (at your option) the GNU General
28** Public license version 3 or any later version approved by the KDE Free
29** Qt Foundation. The licenses are as published by the Free Software
30** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31** included in the packaging of this file. Please review the following
32** information to ensure the GNU General Public License requirements will
33** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34** https://www.gnu.org/licenses/gpl-3.0.html.
35**
36** $QT_END_LICENSE$
37**
38****************************************************************************/
39
40#include "qbezier_p.h"
41#include <qdebug.h>
42#include <qline.h>
43#include <qmath.h>
44#include <qpolygon.h>
45
46#include <private/qnumeric_p.h>
47
48#include <tuple> // for std::tie()
49
50QT_BEGIN_NAMESPACE
51
52//#define QDEBUG_BEZIER
53
54/*!
55 \internal
56*/
57QPolygonF QBezier::toPolygon(qreal bezier_flattening_threshold) const
58{
59 // flattening is done by splitting the bezier until we can replace the segment by a straight
60 // line. We split further until the control points are close enough to the line connecting the
61 // boundary points.
62 //
63 // the Distance of a point p from a line given by the points (a,b) is given by:
64 //
65 // d = abs( (bx - ax)(ay - py) - (by - ay)(ax - px) ) / line_length
66 //
67 // We can stop splitting if both control points are close enough to the line.
68 // To make the algorithm faster we use the manhattan length of the line.
69
70 QPolygonF polygon;
71 polygon.append(QPointF(x1, y1));
72 addToPolygon(&polygon, bezier_flattening_threshold);
73 return polygon;
74}
75
76QBezier QBezier::mapBy(const QTransform &transform) const
77{
78 return QBezier::fromPoints(transform.map(pt1()), transform.map(pt2()), transform.map(pt3()), transform.map(pt4()));
79}
80
81QBezier QBezier::getSubRange(qreal t0, qreal t1) const
82{
83 QBezier result;
84 QBezier temp;
85
86 // cut at t1
87 if (qFuzzyIsNull(t1 - qreal(1.))) {
88 result = *this;
89 } else {
90 temp = *this;
91 temp.parameterSplitLeft(t1, &result);
92 }
93
94 // cut at t0
95 if (!qFuzzyIsNull(t0))
96 result.parameterSplitLeft(t0 / t1, &temp);
97
98 return result;
99}
100
101void QBezier::addToPolygon(QPolygonF *polygon, qreal bezier_flattening_threshold) const
102{
103 QBezier beziers[10];
104 int levels[10];
105 beziers[0] = *this;
106 levels[0] = 9;
107 int top = 0;
108
109 while (top >= 0) {
110 QBezier *b = &beziers[top];
111 // check if we can pop the top bezier curve from the stack
112 qreal y4y1 = b->y4 - b->y1;
113 qreal x4x1 = b->x4 - b->x1;
114 qreal l = qAbs(x4x1) + qAbs(y4y1);
115 qreal d;
116 if (l > 1.) {
117 d = qAbs( (x4x1)*(b->y1 - b->y2) - (y4y1)*(b->x1 - b->x2) )
118 + qAbs( (x4x1)*(b->y1 - b->y3) - (y4y1)*(b->x1 - b->x3) );
119 } else {
120 d = qAbs(b->x1 - b->x2) + qAbs(b->y1 - b->y2) +
121 qAbs(b->x1 - b->x3) + qAbs(b->y1 - b->y3);
122 l = 1.;
123 }
124 if (d < bezier_flattening_threshold * l || levels[top] == 0) {
125 // good enough, we pop it off and add the endpoint
126 polygon->append(QPointF(b->x4, b->y4));
127 --top;
128 } else {
129 // split, second half of the polygon goes lower into the stack
130 std::tie(b[1], b[0]) = b->split();
131 levels[top + 1] = --levels[top];
132 ++top;
133 }
134 }
135}
136
137void QBezier::addToPolygon(QDataBuffer<QPointF> &polygon, qreal bezier_flattening_threshold) const
138{
139 QBezier beziers[10];
140 int levels[10];
141 beziers[0] = *this;
142 levels[0] = 9;
143 int top = 0;
144
145 while (top >= 0) {
146 QBezier *b = &beziers[top];
147 // check if we can pop the top bezier curve from the stack
148 qreal y4y1 = b->y4 - b->y1;
149 qreal x4x1 = b->x4 - b->x1;
150 qreal l = qAbs(x4x1) + qAbs(y4y1);
151 qreal d;
152 if (l > 1.) {
153 d = qAbs( (x4x1)*(b->y1 - b->y2) - (y4y1)*(b->x1 - b->x2) )
154 + qAbs( (x4x1)*(b->y1 - b->y3) - (y4y1)*(b->x1 - b->x3) );
155 } else {
156 d = qAbs(b->x1 - b->x2) + qAbs(b->y1 - b->y2) +
157 qAbs(b->x1 - b->x3) + qAbs(b->y1 - b->y3);
158 l = 1.;
159 }
160 if (d < bezier_flattening_threshold * l || levels[top] == 0) {
161 // good enough, we pop it off and add the endpoint
162 polygon.add(QPointF(b->x4, b->y4));
163 --top;
164 } else {
165 // split, second half of the polygon goes lower into the stack
166 std::tie(b[1], b[0]) = b->split();
167 levels[top + 1] = --levels[top];
168 ++top;
169 }
170 }
171}
172
173QRectF QBezier::bounds() const
174{
175 qreal xmin = x1;
176 qreal xmax = x1;
177 if (x2 < xmin)
178 xmin = x2;
179 else if (x2 > xmax)
180 xmax = x2;
181 if (x3 < xmin)
182 xmin = x3;
183 else if (x3 > xmax)
184 xmax = x3;
185 if (x4 < xmin)
186 xmin = x4;
187 else if (x4 > xmax)
188 xmax = x4;
189
190 qreal ymin = y1;
191 qreal ymax = y1;
192 if (y2 < ymin)
193 ymin = y2;
194 else if (y2 > ymax)
195 ymax = y2;
196 if (y3 < ymin)
197 ymin = y3;
198 else if (y3 > ymax)
199 ymax = y3;
200 if (y4 < ymin)
201 ymin = y4;
202 else if (y4 > ymax)
203 ymax = y4;
204 return QRectF(xmin, ymin, xmax-xmin, ymax-ymin);
205}
206
207
208enum ShiftResult {
209 Ok,
210 Discard,
211 Split,
212 Circle
213};
214
215static ShiftResult good_offset(const QBezier *b1, const QBezier *b2, qreal offset, qreal threshold)
216{
217 const qreal o2 = offset*offset;
218 const qreal max_dist_line = threshold*offset*offset;
219 const qreal max_dist_normal = threshold*offset;
220 const qreal spacing = qreal(0.25);
221 for (qreal i = spacing; i < qreal(0.99); i += spacing) {
222 QPointF p1 = b1->pointAt(i);
223 QPointF p2 = b2->pointAt(i);
224 qreal d = (p1.x() - p2.x())*(p1.x() - p2.x()) + (p1.y() - p2.y())*(p1.y() - p2.y());
225 if (qAbs(d - o2) > max_dist_line)
226 return Split;
227
228 QPointF normalPoint = b1->normalVector(i);
229 qreal l = qAbs(normalPoint.x()) + qAbs(normalPoint.y());
230 if (l != qreal(0.0)) {
231 d = qAbs( normalPoint.x()*(p1.y() - p2.y()) - normalPoint.y()*(p1.x() - p2.x()) ) / l;
232 if (d > max_dist_normal)
233 return Split;
234 }
235 }
236 return Ok;
237}
238
239QT_WARNING_DISABLE_FLOAT_COMPARE
240
241static ShiftResult shift(const QBezier *orig, QBezier *shifted, qreal offset, qreal threshold)
242{
243 int map[4];
244 bool p1_p2_equal = qFuzzyCompare(orig->x1, orig->x2) && qFuzzyCompare(orig->y1, orig->y2);
245 bool p2_p3_equal = qFuzzyCompare(orig->x2, orig->x3) && qFuzzyCompare(orig->y2, orig->y3);
246 bool p3_p4_equal = qFuzzyCompare(orig->x3, orig->x4) && qFuzzyCompare(orig->y3, orig->y4);
247
248 QPointF points[4];
249 int np = 0;
250 points[np] = QPointF(orig->x1, orig->y1);
251 map[0] = 0;
252 ++np;
253 if (!p1_p2_equal) {
254 points[np] = QPointF(orig->x2, orig->y2);
255 ++np;
256 }
257 map[1] = np - 1;
258 if (!p2_p3_equal) {
259 points[np] = QPointF(orig->x3, orig->y3);
260 ++np;
261 }
262 map[2] = np - 1;
263 if (!p3_p4_equal) {
264 points[np] = QPointF(orig->x4, orig->y4);
265 ++np;
266 }
267 map[3] = np - 1;
268 if (np == 1)
269 return Discard;
270
271 QRectF b = orig->bounds();
272 if (np == 4 && b.width() < .1*offset && b.height() < .1*offset) {
273 qreal l = (orig->x1 - orig->x2)*(orig->x1 - orig->x2) +
274 (orig->y1 - orig->y2)*(orig->y1 - orig->y2) *
275 (orig->x3 - orig->x4)*(orig->x3 - orig->x4) +
276 (orig->y3 - orig->y4)*(orig->y3 - orig->y4);
277 qreal dot = (orig->x1 - orig->x2)*(orig->x3 - orig->x4) +
278 (orig->y1 - orig->y2)*(orig->y3 - orig->y4);
279 if (dot < 0 && dot*dot < 0.8*l)
280 // the points are close and reverse dirction. Approximate the whole
281 // thing by a semi circle
282 return Circle;
283 }
284
285 QPointF points_shifted[4];
286
287 QLineF prev = QLineF(QPointF(), points[1] - points[0]);
288 if (!prev.length())
289 return Discard;
290 QPointF prev_normal = prev.normalVector().unitVector().p2();
291
292 points_shifted[0] = points[0] + offset * prev_normal;
293
294 for (int i = 1; i < np - 1; ++i) {
295 QLineF next = QLineF(QPointF(), points[i + 1] - points[i]);
296 QPointF next_normal = next.normalVector().unitVector().p2();
297
298 QPointF normal_sum = prev_normal + next_normal;
299
300 qreal r = qreal(1.0) + prev_normal.x() * next_normal.x()
301 + prev_normal.y() * next_normal.y();
302
303 if (qFuzzyIsNull(r)) {
304 points_shifted[i] = points[i] + offset * prev_normal;
305 } else {
306 qreal k = offset / r;
307 points_shifted[i] = points[i] + k * normal_sum;
308 }
309
310 prev_normal = next_normal;
311 }
312
313 points_shifted[np - 1] = points[np - 1] + offset * prev_normal;
314
315 *shifted = QBezier::fromPoints(points_shifted[map[0]], points_shifted[map[1]],
316 points_shifted[map[2]], points_shifted[map[3]]);
317
318 if (np > 2)
319 return good_offset(orig, shifted, offset, threshold);
320 return Ok;
321}
322
323// This value is used to determine the length of control point vectors
324// when approximating arc segments as curves. The factor is multiplied
325// with the radius of the circle.
326#define KAPPA qreal(0.5522847498)
327
328
329static bool addCircle(const QBezier *b, qreal offset, QBezier *o)
330{
331 QPointF normals[3];
332
333 normals[0] = QPointF(b->y2 - b->y1, b->x1 - b->x2);
334 qreal dist = qSqrt(normals[0].x()*normals[0].x() + normals[0].y()*normals[0].y());
335 if (qFuzzyIsNull(dist))
336 return false;
337 normals[0] /= dist;
338 normals[2] = QPointF(b->y4 - b->y3, b->x3 - b->x4);
339 dist = qSqrt(normals[2].x()*normals[2].x() + normals[2].y()*normals[2].y());
340 if (qFuzzyIsNull(dist))
341 return false;
342 normals[2] /= dist;
343
344 normals[1] = QPointF(b->x1 - b->x2 - b->x3 + b->x4, b->y1 - b->y2 - b->y3 + b->y4);
345 normals[1] /= -1*qSqrt(normals[1].x()*normals[1].x() + normals[1].y()*normals[1].y());
346
347 qreal angles[2];
348 qreal sign = 1.;
349 for (int i = 0; i < 2; ++i) {
350 qreal cos_a = normals[i].x()*normals[i+1].x() + normals[i].y()*normals[i+1].y();
351 if (cos_a > 1.)
352 cos_a = 1.;
353 if (cos_a < -1.)
354 cos_a = -1;
355 angles[i] = qAcos(cos_a) * qreal(M_1_PI);
356 }
357
358 if (angles[0] + angles[1] > 1.) {
359 // more than 180 degrees
360 normals[1] = -normals[1];
361 angles[0] = 1. - angles[0];
362 angles[1] = 1. - angles[1];
363 sign = -1.;
364
365 }
366
367 QPointF circle[3];
368 circle[0] = QPointF(b->x1, b->y1) + normals[0]*offset;
369 circle[1] = QPointF(qreal(0.5)*(b->x1 + b->x4), qreal(0.5)*(b->y1 + b->y4)) + normals[1]*offset;
370 circle[2] = QPointF(b->x4, b->y4) + normals[2]*offset;
371
372 for (int i = 0; i < 2; ++i) {
373 qreal kappa = qreal(2.0) * KAPPA * sign * offset * angles[i];
374
375 o->x1 = circle[i].x();
376 o->y1 = circle[i].y();
377 o->x2 = circle[i].x() - normals[i].y()*kappa;
378 o->y2 = circle[i].y() + normals[i].x()*kappa;
379 o->x3 = circle[i+1].x() + normals[i+1].y()*kappa;
380 o->y3 = circle[i+1].y() - normals[i+1].x()*kappa;
381 o->x4 = circle[i+1].x();
382 o->y4 = circle[i+1].y();
383
384 ++o;
385 }
386 return true;
387}
388
389int QBezier::shifted(QBezier *curveSegments, int maxSegments, qreal offset, float threshold) const
390{
391 Q_ASSERT(curveSegments);
392 Q_ASSERT(maxSegments > 0);
393
394 if (qFuzzyCompare(x1, x2) && qFuzzyCompare(x1, x3) && qFuzzyCompare(x1, x4) &&
395 qFuzzyCompare(y1, y2) && qFuzzyCompare(y1, y3) && qFuzzyCompare(y1, y4))
396 return 0;
397
398 --maxSegments;
399 QBezier beziers[10];
400redo:
401 beziers[0] = *this;
402 QBezier *b = beziers;
403 QBezier *o = curveSegments;
404
405 while (b >= beziers) {
406 int stack_segments = b - beziers + 1;
407 if ((stack_segments == 10) || (o - curveSegments == maxSegments - stack_segments)) {
408 threshold *= qreal(1.5);
409 if (threshold > qreal(2.0))
410 goto give_up;
411 goto redo;
412 }
413 ShiftResult res = shift(b, o, offset, threshold);
414 if (res == Discard) {
415 --b;
416 } else if (res == Ok) {
417 ++o;
418 --b;
419 } else if (res == Circle && maxSegments - (o - curveSegments) >= 2) {
420 // add semi circle
421 if (addCircle(b, offset, o))
422 o += 2;
423 --b;
424 } else {
425 std::tie(b[1], b[0]) = b->split();
426 ++b;
427 }
428 }
429
430give_up:
431 while (b >= beziers) {
432 ShiftResult res = shift(b, o, offset, threshold);
433
434 // if res isn't Ok or Split then *o is undefined
435 if (res == Ok || res == Split)
436 ++o;
437
438 --b;
439 }
440
441 Q_ASSERT(o - curveSegments <= maxSegments);
442 return o - curveSegments;
443}
444
445#ifdef QDEBUG_BEZIER
446static QDebug operator<<(QDebug dbg, const QBezier &bz)
447{
448 dbg << '[' << bz.x1<< ", " << bz.y1 << "], "
449 << '[' << bz.x2 <<", " << bz.y2 << "], "
450 << '[' << bz.x3 <<", " << bz.y3 << "], "
451 << '[' << bz.x4 <<", " << bz.y4 << ']';
452 return dbg;
453}
454#endif
455
456qreal QBezier::length(qreal error) const
457{
458 qreal length = qreal(0.0);
459
460 addIfClose(&length, error);
461
462 return length;
463}
464
465void QBezier::addIfClose(qreal *length, qreal error) const
466{
467 qreal len = qreal(0.0); /* arc length */
468 qreal chord; /* chord length */
469
470 len = len + QLineF(QPointF(x1, y1),QPointF(x2, y2)).length();
471 len = len + QLineF(QPointF(x2, y2),QPointF(x3, y3)).length();
472 len = len + QLineF(QPointF(x3, y3),QPointF(x4, y4)).length();
473
474 chord = QLineF(QPointF(x1, y1),QPointF(x4, y4)).length();
475
476 if((len-chord) > error) {
477 const auto halves = split(); /* split in two */
478 halves.first.addIfClose(length, error); /* try left side */
479 halves.second.addIfClose(length, error); /* try right side */
480 return;
481 }
482
483 *length = *length + len;
484
485 return;
486}
487
488qreal QBezier::tForY(qreal t0, qreal t1, qreal y) const
489{
490 qreal py0 = pointAt(t0).y();
491 qreal py1 = pointAt(t1).y();
492
493 if (py0 > py1) {
494 qSwap(py0, py1);
495 qSwap(t0, t1);
496 }
497
498 Q_ASSERT(py0 <= py1);
499
500 if (py0 >= y)
501 return t0;
502 else if (py1 <= y)
503 return t1;
504
505 Q_ASSERT(py0 < y && y < py1);
506
507 qreal lt = t0;
508 qreal dt;
509 do {
510 qreal t = qreal(0.5) * (t0 + t1);
511
512 qreal a, b, c, d;
513 QBezier::coefficients(t, a, b, c, d);
514 qreal yt = a * y1 + b * y2 + c * y3 + d * y4;
515
516 if (yt < y) {
517 t0 = t;
518 py0 = yt;
519 } else {
520 t1 = t;
521 py1 = yt;
522 }
523 dt = lt - t;
524 lt = t;
525 } while (qAbs(dt) > qreal(1e-7));
526
527 return t0;
528}
529
530int QBezier::stationaryYPoints(qreal &t0, qreal &t1) const
531{
532 // y(t) = (1 - t)^3 * y1 + 3 * (1 - t)^2 * t * y2 + 3 * (1 - t) * t^2 * y3 + t^3 * y4
533 // y'(t) = 3 * (-(1-2t+t^2) * y1 + (1 - 4 * t + 3 * t^2) * y2 + (2 * t - 3 * t^2) * y3 + t^2 * y4)
534 // y'(t) = 3 * ((-y1 + 3 * y2 - 3 * y3 + y4)t^2 + (2 * y1 - 4 * y2 + 2 * y3)t + (-y1 + y2))
535
536 const qreal a = -y1 + 3 * y2 - 3 * y3 + y4;
537 const qreal b = 2 * y1 - 4 * y2 + 2 * y3;
538 const qreal c = -y1 + y2;
539
540 if (qFuzzyIsNull(a)) {
541 if (qFuzzyIsNull(b))
542 return 0;
543
544 t0 = -c / b;
545 return t0 > 0 && t0 < 1;
546 }
547
548 qreal reciprocal = b * b - 4 * a * c;
549
550 if (qFuzzyIsNull(reciprocal)) {
551 t0 = -b / (2 * a);
552 return t0 > 0 && t0 < 1;
553 } else if (reciprocal > 0) {
554 qreal temp = qSqrt(reciprocal);
555
556 t0 = (-b - temp)/(2*a);
557 t1 = (-b + temp)/(2*a);
558
559 if (t1 < t0)
560 qSwap(t0, t1);
561
562 int count = 0;
563 qreal t[2] = { 0, 1 };
564
565 if (t0 > 0 && t0 < 1)
566 t[count++] = t0;
567 if (t1 > 0 && t1 < 1)
568 t[count++] = t1;
569
570 t0 = t[0];
571 t1 = t[1];
572
573 return count;
574 }
575
576 return 0;
577}
578
579qreal QBezier::tAtLength(qreal l) const
580{
581 qreal len = length();
582 qreal t = qreal(1.0);
583 const qreal error = qreal(0.01);
584 if (l > len || qFuzzyCompare(l, len))
585 return t;
586
587 t *= qreal(0.5);
588 //int iters = 0;
589 //qDebug()<<"LEN is "<<l<<len;
590 qreal lastBigger = qreal(1.0);
591 while (1) {
592 //qDebug()<<"\tt is "<<t;
593 QBezier right = *this;
594 QBezier left;
595 right.parameterSplitLeft(t, &left);
596 qreal lLen = left.length();
597 if (qAbs(lLen - l) < error)
598 break;
599
600 if (lLen < l) {
601 t += (lastBigger - t) * qreal(0.5);
602 } else {
603 lastBigger = t;
604 t -= t * qreal(0.5);
605 }
606 //++iters;
607 }
608 //qDebug()<<"number of iters is "<<iters;
609 return t;
610}
611
612QBezier QBezier::bezierOnInterval(qreal t0, qreal t1) const
613{
614 if (t0 == 0 && t1 == 1)
615 return *this;
616
617 QBezier bezier = *this;
618
619 QBezier result;
620 bezier.parameterSplitLeft(t0, &result);
621 qreal trueT = (t1-t0)/(1-t0);
622 bezier.parameterSplitLeft(trueT, &result);
623
624 return result;
625}
626
627QT_END_NAMESPACE
628