forked from paperjs/paper.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCurve.js
More file actions
1502 lines (1419 loc) · 48.4 KB
/
Copy pathCurve.js
File metadata and controls
1502 lines (1419 loc) · 48.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
* http://paperjs.org/
*
* Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
* http://lehni.org/ & http://jonathanpuckey.com/
*
* Distributed under the MIT license. See LICENSE file for details.
*
* All rights reserved.
*/
/**
* @name Curve
*
* @class The Curve object represents the parts of a path that are connected by
* two following {@link Segment} objects. The curves of a path can be accessed
* through its {@link Path#curves} array.
*
* While a segment describe the anchor point and its incoming and outgoing
* handles, a Curve object describes the curve passing between two such
* segments. Curves and segments represent two different ways of looking at the
* same thing, but focusing on different aspects. Curves for example offer many
* convenient ways to work with parts of the path, finding lengths, positions or
* tangents at given offsets.
*/
var Curve = Base.extend(/** @lends Curve# */{
_class: 'Curve',
/**
* Creates a new curve object.
*
* @name Curve#initialize
* @param {Segment} segment1
* @param {Segment} segment2
*/
/**
* Creates a new curve object.
*
* @name Curve#initialize
* @param {Point} point1
* @param {Point} handle1
* @param {Point} handle2
* @param {Point} point2
*/
/**
* Creates a new curve object.
*
* @name Curve#initialize
* @ignore
* @param {Number} x1
* @param {Number} y1
* @param {Number} handle1x
* @param {Number} handle1y
* @param {Number} handle2x
* @param {Number} handle2y
* @param {Number} x2
* @param {Number} y2
*/
initialize: function Curve(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) {
var count = arguments.length;
if (count === 3) {
// Undocumented internal constructor, used by Path#getCurves()
// new Segment(path, segment1, segment2);
this._path = arg0;
this._segment1 = arg1;
this._segment2 = arg2;
} else if (count === 0) {
this._segment1 = new Segment();
this._segment2 = new Segment();
} else if (count === 1) {
// new Segment(segment);
// Note: This copies from existing segments through bean getters
this._segment1 = new Segment(arg0.segment1);
this._segment2 = new Segment(arg0.segment2);
} else if (count === 2) {
// new Segment(segment1, segment2);
this._segment1 = new Segment(arg0);
this._segment2 = new Segment(arg1);
} else {
var point1, handle1, handle2, point2;
if (count === 4) {
point1 = arg0;
handle1 = arg1;
handle2 = arg2;
point2 = arg3;
} else if (count === 8) {
// Convert getValue() array back to points and handles so we
// can create segments for those.
point1 = [arg0, arg1];
point2 = [arg6, arg7];
handle1 = [arg2 - arg0, arg3 - arg1];
handle2 = [arg4 - arg6, arg5 - arg7];
}
this._segment1 = new Segment(point1, null, handle1);
this._segment2 = new Segment(point2, handle2, null);
}
},
_changed: function() {
// Clear cached values.
delete this._length;
delete this._bounds;
},
/**
* The first anchor point of the curve.
*
* @type Point
* @bean
*/
getPoint1: function() {
return this._segment1._point;
},
setPoint1: function(point) {
point = Point.read(arguments);
this._segment1._point.set(point.x, point.y);
},
/**
* The second anchor point of the curve.
*
* @type Point
* @bean
*/
getPoint2: function() {
return this._segment2._point;
},
setPoint2: function(point) {
point = Point.read(arguments);
this._segment2._point.set(point.x, point.y);
},
/**
* The handle point that describes the tangent in the first anchor point.
*
* @type Point
* @bean
*/
getHandle1: function() {
return this._segment1._handleOut;
},
setHandle1: function(point) {
point = Point.read(arguments);
this._segment1._handleOut.set(point.x, point.y);
},
/**
* The handle point that describes the tangent in the second anchor point.
*
* @type Point
* @bean
*/
getHandle2: function() {
return this._segment2._handleIn;
},
setHandle2: function(point) {
point = Point.read(arguments);
this._segment2._handleIn.set(point.x, point.y);
},
/**
* The first segment of the curve.
*
* @type Segment
* @bean
*/
getSegment1: function() {
return this._segment1;
},
/**
* The second segment of the curve.
*
* @type Segment
* @bean
*/
getSegment2: function() {
return this._segment2;
},
/**
* The path that the curve belongs to.
*
* @type Path
* @bean
*/
getPath: function() {
return this._path;
},
/**
* The index of the curve in the {@link Path#curves} array.
*
* @type Number
* @bean
*/
getIndex: function() {
return this._segment1._index;
},
/**
* The next curve in the {@link Path#curves} array that the curve
* belongs to.
*
* @type Curve
* @bean
*/
getNext: function() {
var curves = this._path && this._path._curves;
return curves && (curves[this._segment1._index + 1]
|| this._path._closed && curves[0]) || null;
},
/**
* The previous curve in the {@link Path#curves} array that the curve
* belongs to.
*
* @type Curve
* @bean
*/
getPrevious: function() {
var curves = this._path && this._path._curves;
return curves && (curves[this._segment1._index - 1]
|| this._path._closed && curves[curves.length - 1]) || null;
},
/**
* Specifies whether the handles of the curve are selected.
*
* @type Boolean
* @bean
*/
isSelected: function() {
return this.getHandle1().isSelected() && this.getHandle2().isSelected();
},
setSelected: function(selected) {
this.getHandle1().setSelected(selected);
this.getHandle2().setSelected(selected);
},
getValues: function() {
return Curve.getValues(this._segment1, this._segment2);
},
getPoints: function() {
// Convert to array of absolute points
var coords = this.getValues(),
points = [];
for (var i = 0; i < 8; i += 2)
points.push(new Point(coords[i], coords[i + 1]));
return points;
},
// DOCS: document Curve#getLength(from, to)
/**
* The approximated length of the curve in points.
*
* @type Number
* @bean
*/
// Hide parameters from Bootstrap so it injects bean too
getLength: function(/* from, to */) {
var from = arguments[0],
to = arguments[1],
fullLength = arguments.length === 0 || from === 0 && to === 1;
if (fullLength && this._length != null)
return this._length;
var length = Curve.getLength(this.getValues(), from, to);
if (fullLength)
this._length = length;
return length;
},
getArea: function() {
return Curve.getArea(this.getValues());
},
getPart: function(from, to) {
return new Curve(Curve.getPart(this.getValues(), from, to));
},
/**
* Checks if this curve is linear, meaning it does not define any curve
* handle.
* @return {Boolean} {@true the curve is linear}
*/
isLinear: function() {
return this._segment1._handleOut.isZero()
&& this._segment2._handleIn.isZero();
},
getIntersections: function(curve) {
return Curve.getIntersections(this.getValues(), curve.getValues(),
this, curve, []);
},
// TODO: adjustThroughPoint
/**
* Returns a reversed version of the curve, without modifying the curve
* itself.
*
* @return {Curve} a reversed version of the curve
*/
reverse: function() {
return new Curve(this._segment2.reverse(), this._segment1.reverse());
},
/**
* Private method that handles all types of offset / isParameter pairs and
* converts it to a curve parameter.
*/
_getParameter: function(offset, isParameter) {
return isParameter
? offset
// Accept CurveLocation objects, and objects that act like
// them:
: offset && offset.curve === this
? offset.parameter
: offset === undefined && isParameter === undefined
? 0.5 // default is in the middle
: this.getParameterAt(offset, 0);
},
/**
* Divides the curve into two curves at the given offset. The curve itself
* is modified and becomes the first part, the second part is returned as a
* new curve. If the modified curve belongs to a path item, the second part
* is also added to the path.
*
* @name Curve#divide
* @function
* @param {Number} [offset=0.5] the offset on the curve at which to split,
* or the curve time parameter if {@code isParameter} is {@code true}
* @param {Boolean} [isParameter=false] pass {@code true} if {@code offset}
* is a curve time parameter.
* @return {Curve} the second part of the divided curve
*/
// TODO: Rename to divideAt()?
divide: function(offset, isParameter) {
var parameter = this._getParameter(offset, isParameter),
res = null;
if (parameter > 0 && parameter < 1) {
var parts = Curve.subdivide(this.getValues(), parameter),
isLinear = this.isLinear(),
left = parts[0],
right = parts[1];
// Write back the results:
if (!isLinear) {
this._segment1._handleOut.set(left[2] - left[0],
left[3] - left[1]);
// segment2 is the end segment. By inserting newSegment
// between segment1 and 2, 2 becomes the end segment.
// Convert absolute -> relative
this._segment2._handleIn.set(right[4] - right[6],
right[5] - right[7]);
}
// Create the new segment, convert absolute -> relative:
var x = left[6], y = left[7],
segment = new Segment(new Point(x, y),
!isLinear && new Point(left[4] - x, left[5] - y),
!isLinear && new Point(right[2] - x, right[3] - y));
// Insert it in the segments list, if needed:
if (this._path) {
// Insert at the end if this curve is a closing curve of a
// closed path, since otherwise it would be inserted at 0.
if (this._segment1._index > 0 && this._segment2._index === 0) {
this._path.add(segment);
} else {
this._path.insert(this._segment2._index, segment);
}
// The way Path#_add handles curves, this curve will always
// become the owner of the newly inserted segment.
// TODO: I expect this.getNext() to produce the correct result,
// but since we're inserting differently in _add (something
// linked with CurveLocation#divide()), this is not the case...
res = this; // this.getNext();
} else {
// otherwise create it from the result of split
var end = this._segment2;
this._segment2 = segment;
res = new Curve(segment, end);
}
}
return res;
},
/**
* Splits the path this curve belongs to at the given offset. After
* splitting, the path will be open. If the path was open already, splitting
* will result in two paths.
*
* @name Curve#split
* @function
* @param {Number} [offset=0.5] the offset on the curve at which to split,
* or the curve time parameter if {@code isParameter} is {@code true}
* @param {Boolean} [isParameter=false] pass {@code true} if {@code offset}
* is a curve time parameter.
* @return {Path} the newly created path after splitting, if any
* @see Path#split(index, parameter)
*/
// TODO: Rename to splitAt()?
split: function(offset, isParameter) {
return this._path
? this._path.split(this._segment1._index,
this._getParameter(offset, isParameter))
: null;
},
/**
* Returns a copy of the curve.
*
* @return {Curve}
*/
clone: function() {
return new Curve(this._segment1, this._segment2);
},
/**
* @return {String} a string representation of the curve
*/
toString: function() {
var parts = [ 'point1: ' + this._segment1._point ];
if (!this._segment1._handleOut.isZero())
parts.push('handle1: ' + this._segment1._handleOut);
if (!this._segment2._handleIn.isZero())
parts.push('handle2: ' + this._segment2._handleIn);
parts.push('point2: ' + this._segment2._point);
return '{ ' + parts.join(', ') + ' }';
},
// Mess with indentation in order to get more line-space below...
statics: {
getValues: function(segment1, segment2) {
var p1 = segment1._point,
h1 = segment1._handleOut,
h2 = segment2._handleIn,
p2 = segment2._point;
return [
p1._x, p1._y,
p1._x + h1._x, p1._y + h1._y,
p2._x + h2._x, p2._y + h2._y,
p2._x, p2._y
];
},
evaluate: function(v, t, type) {
var p1x = v[0], p1y = v[1],
c1x = v[2], c1y = v[3],
c2x = v[4], c2y = v[5],
p2x = v[6], p2y = v[7],
x, y;
// Handle special case at beginning / end of curve
if (type === 0 && (t === 0 || t === 1)) {
x = t === 0 ? p1x : p2x;
y = t === 0 ? p1y : p2y;
} else {
// Calculate the polynomial coefficients.
var cx = 3 * (c1x - p1x),
bx = 3 * (c2x - c1x) - cx,
ax = p2x - p1x - cx - bx,
cy = 3 * (c1y - p1y),
by = 3 * (c2y - c1y) - cy,
ay = p2y - p1y - cy - by;
if (type === 0) {
// Calculate the curve point at parameter value t
x = ((ax * t + bx) * t + cx) * t + p1x;
y = ((ay * t + by) * t + cy) * t + p1y;
} else {
// 1: tangent, 1st derivative
// 2: normal, 1st derivative
// 3: curvature, 1st derivative & 2nd derivative
// Prevent tangents and normals of length 0:
// http://stackoverflow.com/questions/10506868/
var tMin = /*#=*/ Numerical.TOLERANCE;
if (t < tMin && c1x == p1x && c1y == p1y
|| t > 1 - tMin && c2x == p2x && c2y == p2y) {
x = c2x - c1x;
y = c2y - c1y;
} else {
// Simply use the derivation of the bezier function for both
// the x and y coordinates:
x = (3 * ax * t + 2 * bx) * t + cx;
y = (3 * ay * t + 2 * by) * t + cy;
}
if (type === 3) {
// Calculate 2nd derivative, and curvature from there:
// http://cagd.cs.byu.edu/~557/text/ch2.pdf page#31
// k = |dx * d2y - dy * d2x| / (( dx^2 + dy^2 )^(3/2))
var x2 = 6 * ax * t + 2 * bx,
y2 = 6 * ay * t + 2 * by;
return (x * y2 - y * x2) / Math.pow(x * x + y * y, 3 / 2);
}
}
}
// The normal is simply the rotated tangent:
return type == 2 ? new Point(y, -x) : new Point(x, y);
},
subdivide: function(v, t) {
var p1x = v[0], p1y = v[1],
c1x = v[2], c1y = v[3],
c2x = v[4], c2y = v[5],
p2x = v[6], p2y = v[7];
if (t === undefined)
t = 0.5;
// Triangle computation, with loops unrolled.
var u = 1 - t,
// Interpolate from 4 to 3 points
p3x = u * p1x + t * c1x, p3y = u * p1y + t * c1y,
p4x = u * c1x + t * c2x, p4y = u * c1y + t * c2y,
p5x = u * c2x + t * p2x, p5y = u * c2y + t * p2y,
// Interpolate from 3 to 2 points
p6x = u * p3x + t * p4x, p6y = u * p3y + t * p4y,
p7x = u * p4x + t * p5x, p7y = u * p4y + t * p5y,
// Interpolate from 2 points to 1 point
p8x = u * p6x + t * p7x, p8y = u * p6y + t * p7y;
// We now have all the values we need to build the subcurves:
return [
[p1x, p1y, p3x, p3y, p6x, p6y, p8x, p8y], // left
[p8x, p8y, p7x, p7y, p5x, p5y, p2x, p2y] // right
];
},
// Converts from the point coordinates (p1, c1, c2, p2) for one axis to
// the polynomial coefficients and solves the polynomial for val
solveCubic: function (v, coord, val, roots, min, max) {
var p1 = v[coord],
c1 = v[coord + 2],
c2 = v[coord + 4],
p2 = v[coord + 6],
c = 3 * (c1 - p1),
b = 3 * (c2 - c1) - c,
a = p2 - p1 - c - b;
return Numerical.solveCubic(a, b, c, p1 - val, roots, min, max);
},
getParameterOf: function(v, x, y) {
// Handle beginnings and end seperately, as they are not detected
// sometimes.
if (Math.abs(v[0] - x) < /*#=*/ Numerical.TOLERANCE
&& Math.abs(v[1] - y) < /*#=*/ Numerical.TOLERANCE)
return 0;
if (Math.abs(v[6] - x) < /*#=*/ Numerical.TOLERANCE
&& Math.abs(v[7] - y) < /*#=*/ Numerical.TOLERANCE)
return 1;
var txs = [],
tys = [],
sx = Curve.solveCubic(v, 0, x, txs),
sy = Curve.solveCubic(v, 1, y, tys),
tx, ty;
// sx, sy == -1 means infinite solutions:
// Loop through all solutions for x and match with solutions for y,
// to see if we either have a matching pair, or infinite solutions
// for one or the other.
for (var cx = 0; sx == -1 || cx < sx;) {
if (sx == -1 || (tx = txs[cx++]) >= 0 && tx <= 1) {
for (var cy = 0; sy == -1 || cy < sy;) {
if (sy == -1 || (ty = tys[cy++]) >= 0 && ty <= 1) {
// Handle infinite solutions by assigning root of
// the other polynomial
if (sx == -1) tx = ty;
else if (sy == -1) ty = tx;
// Use average if we're within tolerance
if (Math.abs(tx - ty) < /*#=*/ Numerical.TOLERANCE)
return (tx + ty) * 0.5;
}
}
// Avoid endless loops here: If sx is infinite and there was
// no fitting ty, there's no solution for this bezier
if (sx == -1)
break;
}
}
return null;
},
// TODO: Find better name
getPart: function(v, from, to) {
if (from > 0)
v = Curve.subdivide(v, from)[1]; // [1] right
// Interpolate the parameter at 'to' in the new curve and
// cut there.
if (to < 1)
v = Curve.subdivide(v, (to - from) / (1 - from))[0]; // [0] left
return v;
},
isLinear: function(v) {
var isZero = Numerical.isZero;
return isZero(v[0] - v[2]) && isZero(v[1] - v[3])
&& isZero(v[4] - v[6]) && isZero(v[5] - v[7]);
},
isFlatEnough: function(v, tolerance) {
// Thanks to Kaspar Fischer and Roger Willcocks for the following:
// http://hcklbrrfnn.files.wordpress.com/2012/08/bez.pdf
var p1x = v[0], p1y = v[1],
c1x = v[2], c1y = v[3],
c2x = v[4], c2y = v[5],
p2x = v[6], p2y = v[7],
ux = 3 * c1x - 2 * p1x - p2x,
uy = 3 * c1y - 2 * p1y - p2y,
vx = 3 * c2x - 2 * p2x - p1x,
vy = 3 * c2y - 2 * p2y - p1y;
return Math.max(ux * ux, vx * vx) + Math.max(uy * uy, vy * vy)
< 10 * tolerance * tolerance;
},
getArea: function(v) {
var p1x = v[0], p1y = v[1],
c1x = v[2], c1y = v[3],
c2x = v[4], c2y = v[5],
p2x = v[6], p2y = v[7];
// http://objectmix.com/graphics/133553-area-closed-bezier-curve.html
return ( 3.0 * c1y * p1x - 1.5 * c1y * c2x
- 1.5 * c1y * p2x - 3.0 * p1y * c1x
- 1.5 * p1y * c2x - 0.5 * p1y * p2x
+ 1.5 * c2y * p1x + 1.5 * c2y * c1x
- 3.0 * c2y * p2x + 0.5 * p2y * p1x
+ 1.5 * p2y * c1x + 3.0 * p2y * c2x) / 10;
},
getBounds: function(v) {
var min = v.slice(0, 2), // Start with values of point1
max = min.slice(), // clone
roots = [0, 0];
for (var i = 0; i < 2; i++)
Curve._addBounds(v[i], v[i + 2], v[i + 4], v[i + 6],
i, 0, min, max, roots);
return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);
},
/**
* Private helper for both Curve.getBounds() and Path.getBounds(), which
* finds the 0-crossings of the derivative of a bezier curve polynomial, to
* determine potential extremas when finding the bounds of a curve.
* Note: padding is only used for Path.getBounds().
*/
_addBounds: function(v0, v1, v2, v3, coord, padding, min, max, roots) {
// Code ported and further optimised from:
// http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
function add(value, padding) {
var left = value - padding,
right = value + padding;
if (left < min[coord])
min[coord] = left;
if (right > max[coord])
max[coord] = right;
}
// Calculate derivative of our bezier polynomial, divided by 3.
// Doing so allows for simpler calculations of a, b, c and leads to the
// same quadratic roots.
var a = 3 * (v1 - v2) - v0 + v3,
b = 2 * (v0 + v2) - 4 * v1,
c = v1 - v0,
count = Numerical.solveQuadratic(a, b, c, roots),
// Add some tolerance for good roots, as t = 0 / 1 are added
// seperately anyhow, and we don't want joins to be added with
// radiuses in getStrokeBounds()
tMin = /*#=*/ Numerical.TOLERANCE,
tMax = 1 - tMin;
// Only add strokeWidth to bounds for points which lie within 0 < t < 1
// The corner cases for cap and join are handled in getStrokeBounds()
add(v3, 0);
for (var i = 0; i < count; i++) {
var t = roots[i],
u = 1 - t;
// Test for good roots and only add to bounds if good.
if (tMin < t && t < tMax)
// Calculate bezier polynomial at t.
add(u * u * u * v0
+ 3 * u * u * t * v1
+ 3 * u * t * t * v2
+ t * t * t * v3,
padding);
}
},
_getWinding: function(v, x, y, roots1, roots2) {
// Implementation of the crossing number algorithm:
// http://en.wikipedia.org/wiki/Point_in_polygon
// Solve the y-axis cubic polynomial for y and count all solutions
// to the right of x as crossings.
var tolerance = /*#=*/ Numerical.TOLERANCE,
abs = Math.abs;
// Looks at the curve's start and end y coordinates to determine
// orientation. This only makes sense for curves with clear orientation,
// which is why we need to split them at y extrema, see below.
// Returns 0 if the curve is outside the boundaries and is not to be
// considered.
function getOrientation(v) {
var y0 = v[1],
y1 = v[7],
dir = 1;
if (y0 > y1) {
var tmp = y0;
y0 = y1;
y1 = tmp;
dir = -1;
}
if (y < y0 || y > y1)
dir = 0;
return dir;
}
if (Curve.isLinear(v)) {
// Special simplified case for handling lines.
var dir = getOrientation(v);
if (!dir)
return 0;
var cross = (v[6] - v[0]) * (y - v[1]) - (v[7] - v[1]) * (x - v[0]);
return (cross < -tolerance ? -1 : 1) == dir ? 0 : dir;
}
// Handle bezier curves. We need to chop them into smaller curves with
// defined orientation, by solving the derrivative curve for Y extrema.
var y0 = v[1],
y1 = v[3],
y2 = v[5],
y3 = v[7];
// Split the curve at y extrema, to get bezier curves with clear
// orientation: Calculate the derivative and find its roots.
var a = 3 * (y1 - y2) - y0 + y3,
b = 2 * (y0 + y2) - 4 * y1,
c = y1 - y0;
// Keep then range to 0 .. 1 (excluding) in the search for y extrema
var count = Numerical.solveQuadratic(a, b, c, roots1, tolerance,
1 - tolerance),
part, // The part of the curve that's chopped off.
rest = v, // The part that's left to be chopped.
t1 = roots1[0], // The first root
winding = 0;
for (var i = 0; i <= count; i++) {
if (i === count) {
part = rest;
} else {
// Divide the curve at t1.
var curves = Curve.subdivide(rest, t1);
part = curves[0];
rest = curves[1];
t1 = roots1[i];
// TODO: Watch for divide by 0
// Now renormalize t1 to the range of the next iteration.
t1 = (roots1[i + 1] - t1) / (1 - t1);
}
// Make sure that the connecting y extrema are flat
if (i > 0)
part[3] = part[1]; // curve2.handle1.y = curve2.point1.y;
if (i < count)
part[5] = rest[1]; // curve1.handle2.y = curve2.point1.y;
var dir = getOrientation(part);
if (!dir)
continue;
// Adjust start and end range depending on if curve was flipped.
// In normal orientation we exclude the end point since it's also
// the start point of the next curve. If flipped, we have to exclude
// the end point instead.
var t2,
px;
// Since we've split at y extrema, there can only be 0, 1, or
// infinite solutions now.
if (Curve.solveCubic(part, 1, y, roots2, -tolerance, 1 + -tolerance)
=== 1) {
t2 = roots2[0];
px = Curve.evaluate(part, t2, 0).x;
} else {
var mid = (part[1] + part[7]) / 2;
// Pick t2 based on the direction of the curve. If y < mid,
// choose the beginning (which is the end of a curve with
// negative orientation, as we're not actually flipping curves).
t2 = y < mid && dir > 0 ? 0 : 1;
// Filter out the end point, as it'll be the start point of the
// next curve.
if (t2 === 1 && y == part[7])
continue;
px = t2 === 0 ? part[0] : part[6];
}
// See if we're touching a horizontal stationary point by looking at
// the tanget's y coordinate.
var flat = abs(Curve.evaluate(part, t2, 1).y) < tolerance;
// Calculate compare tolerance based on curve orientation (dir), to
// add a bit of tolerance when considering points lying on the curve
// as inside. But if we're touching a horizontal stationary point,
// set compare tolerance to -tolerance, since we don't want to step
// side-ways in tolerance based on orientation. This is needed e.g.
// when touching the bottom tip of a circle.
// Pass 1 for Curve.evaluate() type to calculate tangent
if (x >= px + (flat ? -tolerance : tolerance * dir)
// When touching a stationary point, only count it if we're
// actuall on it.
&& !(flat && (abs(t2) < tolerance && x != part[0]
|| abs(t2 - 1) < tolerance && x != part[6]))) {
// If this is a horizontal stationary point, and we're at the
// end of the curve (or at the beginning of a curve with
// negative direction, as we're not actually flipping them),
// flip dir, as the curve is about to change orientation.
winding += flat && abs(t2 - (dir > 0 ? 1 : 0)) < tolerance
? -dir : dir;
}
}
return winding;
}
}}, Base.each(['getBounds', 'getStrokeBounds', 'getHandleBounds', 'getRoughBounds'],
// Note: Although Curve.getBounds() exists, we are using Path.getBounds() to
// determine the bounds of Curve objects with defined segment1 and segment2
// values Curve.getBounds() can be used directly on curve arrays, without
// the need to create a Curve object first, as required by the code that
// finds path interesections.
function(name) {
this[name] = function() {
if (!this._bounds)
this._bounds = {};
var bounds = this._bounds[name];
if (!bounds) {
// Calculate the curve bounds by passing a segment list for the
// curve to the static Path.get*Boudns methods.
bounds = this._bounds[name] = Path[name]([this._segment1,
this._segment2], false, this._path.getStyle());
}
return bounds.clone();
};
},
/** @lends Curve# */{
/**
* The bounding rectangle of the curve excluding stroke width.
*
* @name Curve#getBounds
* @type Rectangle
* @bean
*/
/**
* The bounding rectangle of the curve including stroke width.
*
* @name Curve#getStrokeBounds
* @type Rectangle
* @bean
*/
/**
* The bounding rectangle of the curve including handles.
*
* @name Curve#getHandleBounds
* @type Rectangle
* @bean
*/
/**
* The rough bounding rectangle of the curve that is shure to include all of
* the drawing, including stroke width.
*
* @name Curve#getRoughBounds
* @type Rectangle
* @bean
* @ignore
*/
}), Base.each(['getPoint', 'getTangent', 'getNormal', 'getCurvature'],
// Note: Although Curve.getBounds() exists, we are using Path.getBounds() to
// determine the bounds of Curve objects with defined segment1 and segment2
// values Curve.getBounds() can be used directly on curve arrays, without
// the need to create a Curve object first, as required by the code that
// finds path interesections.
function(name, index) {
this[name + 'At'] = function(offset, isParameter) {
var values = this.getValues();
return Curve.evaluate(values, isParameter
? offset : Curve.getParameterAt(values, offset, 0), index);
};
// Deprecated and undocumented, but keep around for now.
// TODO: Remove once enough time has passed (28.01.2013)
this[name] = function(parameter) {
return Curve.evaluate(this.getValues(), parameter, index);
};
},
/** @lends Curve# */{
/**
* Calculates the curve time parameter of the specified offset on the path,
* relative to the provided start parameter. If offset is a negative value,
* the parameter is searched to the left of the start parameter. If no start
* parameter is provided, a default of {@code 0} for positive values of
* {@code offset} and {@code 1} for negative values of {@code offset}.
* @param {Number} offset
* @param {Number} [start]
* @return {Number} the curve time parameter at the specified offset.
*/
getParameterAt: function(offset, start) {
return Curve.getParameterAt(this.getValues(), offset,
start !== undefined ? start : offset < 0 ? 1 : 0);
},
/**
* Returns the curve time parameter of the specified point if it lies on the
* curve, {@code null} otherwise.
* @param {Point} point the point on the curve.
* @return {Number} the curve time parameter of the specified point.
*/
getParameterOf: function(point) {
point = Point.read(arguments);
return Curve.getParameterOf(this.getValues(), point.x, point.y);
},
/**
* Calculates the curve location at the specified offset or curve time
* parameter.
* @param {Number} offset the offset on the curve, or the curve time
* parameter if {@code isParameter} is {@code true}
* @param {Boolean} [isParameter=false] pass {@code true} if {@code offset}
* is a curve time parameter.
* @return {CurveLocation} the curve location at the specified the offset.
*/
getLocationAt: function(offset, isParameter) {
if (!isParameter)
offset = this.getParameterAt(offset);
return new CurveLocation(this, offset);
},
/**
* Returns the curve location of the specified point if it lies on the
* curve, {@code null} otherwise.
* @param {Point} point the point on the curve.
* @return {CurveLocation} the curve location of the specified point.
*/
getLocationOf: function(point) {
// We need to use point to avoid minification issues and prevent method
// from turning into a bean (by removal of the point argument).
point = Point.read(arguments);
var t = this.getParameterOf(point);
return t != null ? new CurveLocation(this, t) : null;
},
getNearestLocation: function(point) {
point = Point.read(arguments);
var values = this.getValues(),
count = 100,
tolerance = Numerical.TOLERANCE,
minDist = Infinity,
minT = 0;
function refine(t) {
if (t >= 0 && t <= 1) {
var dist = point.getDistance(
Curve.evaluate(values, t, 0), true);
if (dist < minDist) {
minDist = dist;
minT = t;
return true;
}
}
}
for (var i = 0; i <= count; i++)
refine(i / count);
// Now iteratively refine solution until we reach desired precision.
var step = 1 / (count * 2);
while (step > tolerance) {
if (!refine(minT - step) && !refine(minT + step))
step /= 2;
}
var pt = Curve.evaluate(values, minT, 0);
return new CurveLocation(this, minT, pt, null, null, null,
point.getDistance(pt));
},
getNearestPoint: function(point) {
// We need to use point to avoid minification issues and prevent method
// from turning into a bean (by removal of the point argument).
point = Point.read(arguments);
return this.getNearestLocation(point).getPoint();
}
/**
* Returns the point on the curve at the specified offset.
*
* @name Curve#getPointAt
* @function
* @param {Number} offset the offset on the curve, or the curve time
* parameter if {@code isParameter} is {@code true}
* @param {Boolean} [isParameter=false] pass {@code true} if {@code offset}
* is a curve time parameter.
* @return {Point} the point on the curve at the specified offset.
*/
/**
* Returns the tangent vector of the curve at the specified position.
*
* @name Curve#getTangentAt