pathfinder.src.js
72.6 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
/**
* @license Highcharts JS v6.2.0 (2018-10-17)
* Pathfinder
*
* (c) 2016 Øystein Moseng
*
* --- WORK IN PROGRESS ---
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define(function () {
return factory;
});
} else {
factory(Highcharts);
}
}(function (Highcharts) {
var algorithms = (function (H) {
/**
* (c) 2016 Highsoft AS
* Author: Øystein Moseng
*
* License: www.highcharts.com/license
*/
var min = Math.min,
max = Math.max,
abs = Math.abs,
pick = H.pick;
/**
* Get index of last obstacle before xMin. Employs a type of binary search, and
* thus requires that obstacles are sorted by xMin value.
*
* @param {Array} obstacles Array of obstacles to search in.
* @param {Number} xMin The xMin threshold.
* @param {Number} startIx Starting index to search from. Must be within array
* range.
*
* @return {Number} result The index of the last obstacle element before xMin.
*/
function findLastObstacleBefore(obstacles, xMin, startIx) {
var left = startIx || 0, // left limit
right = obstacles.length - 1, // right limit
min = xMin - 0.0000001, // Make sure we include all obstacles at xMin
cursor,
cmp;
while (left <= right) {
cursor = (right + left) >> 1;
cmp = min - obstacles[cursor].xMin;
if (cmp > 0) {
left = cursor + 1;
} else if (cmp < 0) {
right = cursor - 1;
} else {
return cursor;
}
}
return left > 0 ? left - 1 : 0;
}
/**
* Test if a point lays within an obstacle.
*
* @param {Object} obstacle Obstacle to test.
* @param {Object} point Point with x/y props.
*
* @return {Boolean} result Whether point is within the obstacle or not.
*/
function pointWithinObstacle(obstacle, point) {
return (
point.x <= obstacle.xMax &&
point.x >= obstacle.xMin &&
point.y <= obstacle.yMax &&
point.y >= obstacle.yMin
);
}
/**
* Find the index of an obstacle that wraps around a point.
* Returns -1 if not found.
*
* @param {Array} obstacles Obstacles to test.
* @param {Object} point Point with x/y props.
*
* @return {Number} result Ix of the obstacle in the array, or -1 if not found.
*/
function findObstacleFromPoint(obstacles, point) {
var i = findLastObstacleBefore(obstacles, point.x + 1) + 1;
while (i--) {
if (obstacles[i].xMax >= point.x &&
// optimization using lazy evaluation
pointWithinObstacle(obstacles[i], point)) {
return i;
}
}
return -1;
}
/**
* Get SVG path array from array of line segments.
*
* @param {Array} segments The segments to build the path from.
*
* @return {Array} result SVG path array as accepted by the SVG Renderer.
*/
function pathFromSegments(segments) {
var path = [];
if (segments.length) {
path.push('M', segments[0].start.x, segments[0].start.y);
for (var i = 0; i < segments.length; ++i) {
path.push('L', segments[i].end.x, segments[i].end.y);
}
}
return path;
}
/**
* Limits obstacle max/mins in all directions to bounds. Modifies input
* obstacle.
*
* @param {Object} obstacle Obstacle to limit.
* @param {Object} bounds Bounds to use as limit.
*/
function limitObstacleToBounds(obstacle, bounds) {
obstacle.yMin = max(obstacle.yMin, bounds.yMin);
obstacle.yMax = min(obstacle.yMax, bounds.yMax);
obstacle.xMin = max(obstacle.xMin, bounds.xMin);
obstacle.xMax = min(obstacle.xMax, bounds.xMax);
}
// Define the available pathfinding algorithms.
// Algorithms take up to 3 arguments: starting point, ending point, and an
// options object.
var algorithms = {
/**
* Get an SVG path from a starting coordinate to an ending coordinate.
* Draws a straight line.
*
* @param {Object} start Starting coordinate, object with x/y props.
* @param {Object} end Ending coordinate, object with x/y props.
*
* @return {Object} result An object with the SVG path in Array form as
* accepted by the SVG renderer, as well as an array of new obstacles
* making up this path.
*/
straight: function (start, end) {
return {
path: ['M', start.x, start.y, 'L', end.x, end.y],
obstacles: [{ start: start, end: end }]
};
},
/**
* Find a path from a starting coordinate to an ending coordinate, using
* right angles only, and taking only starting/ending obstacle into
* consideration.
*
* Options
* - chartObstacles: Array of chart obstacles to avoid
* - startDirectionX: Optional. True if starting in the X direction.
* If not provided, the algorithm starts in the
* direction that is the furthest between
* start/end.
*
* @param {Object} start Starting coordinate, object with x/y props.
* @param {Object} end Ending coordinate, object with x/y props.
* @param {Object} options Options for the algorithm.
*
* @return {Object} result An object with the SVG path in Array form as
* accepted by the SVG renderer, as well as an array of new obstacles
* making up this path.
*/
simpleConnect: H.extend(function (start, end, options) {
var segments = [],
endSegment,
dir = pick(
options.startDirectionX,
abs(end.x - start.x) > abs(end.y - start.y)
) ? 'x' : 'y',
chartObstacles = options.chartObstacles,
startObstacleIx = findObstacleFromPoint(chartObstacles, start),
endObstacleIx = findObstacleFromPoint(chartObstacles, end),
startObstacle,
endObstacle,
prevWaypoint,
waypoint,
waypoint2,
useMax,
endPoint;
// Return a clone of a point with a property set from a target object,
// optionally with an offset
function copyFromPoint(from, fromKey, to, toKey, offset) {
var point = {
x: from.x,
y: from.y
};
point[fromKey] = to[toKey || fromKey] + (offset || 0);
return point;
}
// Return waypoint outside obstacle
function getMeOut(obstacle, point, direction) {
var useMax = abs(point[direction] - obstacle[direction + 'Min']) >
abs(point[direction] - obstacle[direction + 'Max']);
return copyFromPoint(
point,
direction,
obstacle,
direction + (useMax ? 'Max' : 'Min'),
useMax ? 1 : -1
);
}
// Pull out end point
if (endObstacleIx > -1) {
endObstacle = chartObstacles[endObstacleIx];
waypoint = getMeOut(endObstacle, end, dir);
endSegment = {
start: waypoint,
end: end
};
endPoint = waypoint;
} else {
endPoint = end;
}
// If an obstacle envelops the start point, add a segment to get out,
// and around it.
if (startObstacleIx > -1) {
startObstacle = chartObstacles[startObstacleIx];
waypoint = getMeOut(startObstacle, start, dir);
segments.push({
start: start,
end: waypoint
});
// If we are going back again, switch direction to get around start
// obstacle.
if (
waypoint[dir] > start[dir] === // Going towards max from start
waypoint[dir] > endPoint[dir] // Going towards min to end
) {
dir = dir === 'y' ? 'x' : 'y';
useMax = start[dir] < end[dir];
segments.push({
start: waypoint,
end: copyFromPoint(
waypoint,
dir,
startObstacle,
dir + (useMax ? 'Max' : 'Min'),
useMax ? 1 : -1
)
});
// Switch direction again
dir = dir === 'y' ? 'x' : 'y';
}
}
// We are around the start obstacle. Go towards the end in one
// direction.
prevWaypoint = segments.length ?
segments[segments.length - 1].end :
start;
waypoint = copyFromPoint(prevWaypoint, dir, endPoint);
segments.push({
start: prevWaypoint,
end: waypoint
});
// Final run to end point in the other direction
dir = dir === 'y' ? 'x' : 'y';
waypoint2 = copyFromPoint(waypoint, dir, endPoint);
segments.push({
start: waypoint,
end: waypoint2
});
// Finally add the endSegment
segments.push(endSegment);
return {
path: pathFromSegments(segments),
obstacles: segments
};
}, {
requiresObstacles: true
}),
/**
* Find a path from a starting coordinate to an ending coordinate, taking
* obstacles into consideration. Might not always find the optimal path,
* but is fast, and usually good enough.
*
* Options
* - chartObstacles: Array of chart obstacles to avoid
* - lineObstacles: Array of line obstacles to jump over
* - obstacleMetrics: Object with metrics of chartObstacles cached
* - hardBounds: Hard boundaries to not cross
* - obstacleOptions: Options for the obstacles, including margin
* - startDirectionX: Optional. True if starting in the X direction.
* If not provided, the algorithm starts in the
* direction that is the furthest between
* start/end.
*
* @param {Object} start Starting coordinate, object with x/y props.
* @param {Object} end Ending coordinate, object with x/y props.
* @param {Object} options Options for the algorithm.
*
* @return {Object} result An object with the SVG path in Array form as
* accepted by the SVG renderer, as well as an array of new obstacles
* making up this path.
*/
fastAvoid: H.extend(function (start, end, options) {
/*
Algorithm rules/description
- Find initial direction
- Determine soft/hard max for each direction.
- Move along initial direction until obstacle.
- Change direction.
- If hitting obstacle, first try to change length of previous line
before changing direction again.
Soft min/max x = start/destination x +/- widest obstacle + margin
Soft min/max y = start/destination y +/- tallest obstacle + margin
TODO:
- Make retrospective, try changing prev segment to reduce
corners
- Fix logic for breaking out of end-points - not always picking
the best direction currently
- When going around the end obstacle we should not always go the
shortest route, rather pick the one closer to the end point
*/
var dirIsX = pick(
options.startDirectionX,
abs(end.x - start.x) > abs(end.y - start.y)
),
dir = dirIsX ? 'x' : 'y',
segments,
useMax,
extractedEndPoint,
endSegments = [],
forceObstacleBreak = false, // Used in clearPathTo to keep track of
// when to force break through an obstacle.
// Boundaries to stay within. If beyond soft boundary, prefer to
// change direction ASAP. If at hard max, always change immediately.
metrics = options.obstacleMetrics,
softMinX = min(start.x, end.x) - metrics.maxWidth - 10,
softMaxX = max(start.x, end.x) + metrics.maxWidth + 10,
softMinY = min(start.y, end.y) - metrics.maxHeight - 10,
softMaxY = max(start.y, end.y) + metrics.maxHeight + 10,
// Obstacles
chartObstacles = options.chartObstacles,
startObstacleIx = findLastObstacleBefore(chartObstacles, softMinX),
endObstacleIx = findLastObstacleBefore(chartObstacles, softMaxX);
// How far can you go between two points before hitting an obstacle?
// Does not work for diagonal lines (because it doesn't have to).
function pivotPoint(fromPoint, toPoint, directionIsX) {
var firstPoint,
lastPoint,
highestPoint,
lowestPoint,
i,
searchDirection = fromPoint.x < toPoint.x ? 1 : -1;
if (fromPoint.x < toPoint.x) {
firstPoint = fromPoint;
lastPoint = toPoint;
} else {
firstPoint = toPoint;
lastPoint = fromPoint;
}
if (fromPoint.y < toPoint.y) {
lowestPoint = fromPoint;
highestPoint = toPoint;
} else {
lowestPoint = toPoint;
highestPoint = fromPoint;
}
// Go through obstacle range in reverse if toPoint is before
// fromPoint in the X-dimension.
i = searchDirection < 0 ?
// Searching backwards, start at last obstacle before last point
min(findLastObstacleBefore(chartObstacles, lastPoint.x),
chartObstacles.length - 1) :
// Forwards. Since we're not sorted by xMax, we have to look
// at all obstacles.
0;
// Go through obstacles in this X range
while (chartObstacles[i] && (
searchDirection > 0 && chartObstacles[i].xMin <= lastPoint.x ||
searchDirection < 0 && chartObstacles[i].xMax >= firstPoint.x
)) {
// If this obstacle is between from and to points in a straight
// line, pivot at the intersection.
if (
chartObstacles[i].xMin <= lastPoint.x &&
chartObstacles[i].xMax >= firstPoint.x &&
chartObstacles[i].yMin <= highestPoint.y &&
chartObstacles[i].yMax >= lowestPoint.y
) {
if (directionIsX) {
return {
y: fromPoint.y,
x: fromPoint.x < toPoint.x ?
chartObstacles[i].xMin - 1 :
chartObstacles[i].xMax + 1,
obstacle: chartObstacles[i]
};
}
// else ...
return {
x: fromPoint.x,
y: fromPoint.y < toPoint.y ?
chartObstacles[i].yMin - 1 :
chartObstacles[i].yMax + 1,
obstacle: chartObstacles[i]
};
}
i += searchDirection;
}
return toPoint;
}
/**
* Decide in which direction to dodge or get out of an obstacle.
* Considers desired direction, which way is shortest, soft and hard
* bounds.
*
* Returns a string, either xMin, xMax, yMin or yMax.
*
* @param {Object} obstacle Obstacle to dodge/escape.
* @param {Object} fromPoint Point with x/y props that's
* dodging/escaping.
* @param {Object} toPoint Goal point.
* @param {Boolean} dirIsX Dodge in X dimension.
* @param {Object} bounds Hard and soft boundaries.
*
* @return {Boolean} result Use max or not.
*/
function getDodgeDirection(
obstacle,
fromPoint,
toPoint,
dirIsX,
bounds
) {
var softBounds = bounds.soft,
hardBounds = bounds.hard,
dir = dirIsX ? 'x' : 'y',
toPointMax = { x: fromPoint.x, y: fromPoint.y },
toPointMin = { x: fromPoint.x, y: fromPoint.y },
minPivot,
maxPivot,
maxOutOfSoftBounds = obstacle[dir + 'Max'] >=
softBounds[dir + 'Max'],
minOutOfSoftBounds = obstacle[dir + 'Min'] <=
softBounds[dir + 'Min'],
maxOutOfHardBounds = obstacle[dir + 'Max'] >=
hardBounds[dir + 'Max'],
minOutOfHardBounds = obstacle[dir + 'Min'] <=
hardBounds[dir + 'Min'],
// Find out if we should prefer one direction over the other if
// we can choose freely
minDistance = abs(obstacle[dir + 'Min'] - fromPoint[dir]),
maxDistance = abs(obstacle[dir + 'Max'] - fromPoint[dir]),
// If it's a small difference, pick the one leading towards dest
// point. Otherwise pick the shortest distance
useMax = abs(minDistance - maxDistance) < 10 ?
fromPoint[dir] < toPoint[dir] :
maxDistance < minDistance;
// Check if we hit any obstacles trying to go around in either
// direction.
toPointMin[dir] = obstacle[dir + 'Min'];
toPointMax[dir] = obstacle[dir + 'Max'];
minPivot = pivotPoint(fromPoint, toPointMin, dirIsX)[dir] !==
toPointMin[dir];
maxPivot = pivotPoint(fromPoint, toPointMax, dirIsX)[dir] !==
toPointMax[dir];
useMax = minPivot ?
(maxPivot ? useMax : true) :
(maxPivot ? false : useMax);
// useMax now contains our preferred choice, bounds not taken into
// account. If both or neither direction is out of bounds we want to
// use this.
// Deal with soft bounds
useMax = minOutOfSoftBounds ?
(maxOutOfSoftBounds ? useMax : true) : // Out on min
(maxOutOfSoftBounds ? false : useMax); // Not out on min
// Deal with hard bounds
useMax = minOutOfHardBounds ?
(maxOutOfHardBounds ? useMax : true) : // Out on min
(maxOutOfHardBounds ? false : useMax); // Not out on min
return useMax;
}
// Find a clear path between point
function clearPathTo(fromPoint, toPoint, dirIsX) {
// Don't waste time if we've hit goal
if (fromPoint.x === toPoint.x && fromPoint.y === toPoint.y) {
return [];
}
var dir = dirIsX ? 'x' : 'y',
pivot,
segments,
waypoint,
waypointUseMax,
envelopingObstacle,
secondEnvelopingObstacle,
envelopWaypoint,
obstacleMargin = options.obstacleOptions.margin,
bounds = {
soft: {
xMin: softMinX,
xMax: softMaxX,
yMin: softMinY,
yMax: softMaxY
},
hard: options.hardBounds
};
// If fromPoint is inside an obstacle we have a problem. Break out
// by just going to the outside of this obstacle. We prefer to go to
// the nearest edge in the chosen direction.
envelopingObstacle =
findObstacleFromPoint(chartObstacles, fromPoint);
if (envelopingObstacle > -1) {
envelopingObstacle = chartObstacles[envelopingObstacle];
waypointUseMax = getDodgeDirection(
envelopingObstacle, fromPoint, toPoint, dirIsX, bounds
);
// Cut obstacle to hard bounds to make sure we stay within
limitObstacleToBounds(envelopingObstacle, options.hardBounds);
envelopWaypoint = dirIsX ? {
y: fromPoint.y,
x: envelopingObstacle[waypointUseMax ? 'xMax' : 'xMin'] +
(waypointUseMax ? 1 : -1)
} : {
x: fromPoint.x,
y: envelopingObstacle[waypointUseMax ? 'yMax' : 'yMin'] +
(waypointUseMax ? 1 : -1)
};
// If we crashed into another obstacle doing this, we put the
// waypoint between them instead
secondEnvelopingObstacle = findObstacleFromPoint(
chartObstacles, envelopWaypoint);
if (secondEnvelopingObstacle > -1) {
secondEnvelopingObstacle = chartObstacles[
secondEnvelopingObstacle
];
// Cut obstacle to hard bounds
limitObstacleToBounds(
secondEnvelopingObstacle,
options.hardBounds
);
// Modify waypoint to lay between obstacles
envelopWaypoint[dir] = waypointUseMax ? max(
envelopingObstacle[dir + 'Max'] - obstacleMargin + 1,
(
secondEnvelopingObstacle[dir + 'Min'] +
envelopingObstacle[dir + 'Max']
) / 2
) :
min(
envelopingObstacle[dir + 'Min'] + obstacleMargin - 1,
(
secondEnvelopingObstacle[dir + 'Max'] +
envelopingObstacle[dir + 'Min']
) / 2
);
// We are not going anywhere. If this happens for the first
// time, do nothing. Otherwise, try to go to the extreme of
// the obstacle pair in the current direction.
if (fromPoint.x === envelopWaypoint.x &&
fromPoint.y === envelopWaypoint.y) {
if (forceObstacleBreak) {
envelopWaypoint[dir] = waypointUseMax ?
max(
envelopingObstacle[dir + 'Max'],
secondEnvelopingObstacle[dir + 'Max']
) + 1 :
min(
envelopingObstacle[dir + 'Min'],
secondEnvelopingObstacle[dir + 'Min']
) - 1;
}
// Toggle on if off, and the opposite
forceObstacleBreak = !forceObstacleBreak;
} else {
// This point is not identical to previous.
// Clear break trigger.
forceObstacleBreak = false;
}
}
segments = [{
start: fromPoint,
end: envelopWaypoint
}];
} else { // If not enveloping, use standard pivot calculation
pivot = pivotPoint(fromPoint, {
x: dirIsX ? toPoint.x : fromPoint.x,
y: dirIsX ? fromPoint.y : toPoint.y
}, dirIsX);
segments = [{
start: fromPoint,
end: {
x: pivot.x,
y: pivot.y
}
}];
// Pivot before goal, use a waypoint to dodge obstacle
if (pivot[dirIsX ? 'x' : 'y'] !== toPoint[dirIsX ? 'x' : 'y']) {
// Find direction of waypoint
waypointUseMax = getDodgeDirection(
pivot.obstacle, pivot, toPoint, !dirIsX, bounds
);
// Cut waypoint to hard bounds
limitObstacleToBounds(pivot.obstacle, options.hardBounds);
waypoint = {
x: dirIsX ?
pivot.x :
pivot.obstacle[waypointUseMax ? 'xMax' : 'xMin'] +
(waypointUseMax ? 1 : -1),
y: dirIsX ?
pivot.obstacle[waypointUseMax ? 'yMax' : 'yMin'] +
(waypointUseMax ? 1 : -1) :
pivot.y
};
// We're changing direction here, store that to make sure we
// also change direction when adding the last segment array
// after handling waypoint.
dirIsX = !dirIsX;
segments = segments.concat(clearPathTo({
x: pivot.x,
y: pivot.y
}, waypoint, dirIsX));
}
}
// Get segments for the other direction too
// Recursion is our friend
segments = segments.concat(clearPathTo(
segments[segments.length - 1].end, toPoint, !dirIsX
));
return segments;
}
// Extract point to outside of obstacle in whichever direction is
// closest. Returns new point outside obstacle.
function extractFromObstacle(obstacle, point, goalPoint) {
var dirIsX = min(obstacle.xMax - point.x, point.x - obstacle.xMin) <
min(obstacle.yMax - point.y, point.y - obstacle.yMin),
bounds = {
soft: options.hardBounds,
hard: options.hardBounds
},
useMax = getDodgeDirection(
obstacle, point, goalPoint, dirIsX, bounds
);
return dirIsX ? {
y: point.y,
x: obstacle[useMax ? 'xMax' : 'xMin'] + (useMax ? 1 : -1)
} : {
x: point.x,
y: obstacle[useMax ? 'yMax' : 'yMin'] + (useMax ? 1 : -1)
};
}
// Cut the obstacle array to soft bounds for optimization in large
// datasets.
chartObstacles =
chartObstacles.slice(startObstacleIx, endObstacleIx + 1);
// If an obstacle envelops the end point, move it out of there and add
// a little segment to where it was.
if ((endObstacleIx = findObstacleFromPoint(chartObstacles, end)) > -1) {
extractedEndPoint = extractFromObstacle(
chartObstacles[endObstacleIx],
end,
start
);
endSegments.push({
end: end,
start: extractedEndPoint
});
end = extractedEndPoint;
}
// If it's still inside one or more obstacles, get out of there by
// force-moving towards the start point.
while (
(endObstacleIx = findObstacleFromPoint(chartObstacles, end)) > -1
) {
useMax = end[dir] - start[dir] < 0;
extractedEndPoint = {
x: end.x,
y: end.y
};
extractedEndPoint[dir] = chartObstacles[endObstacleIx][
useMax ? dir + 'Max' : dir + 'Min'
] + (useMax ? 1 : -1);
endSegments.push({
end: end,
start: extractedEndPoint
});
end = extractedEndPoint;
}
// Find the path
segments = clearPathTo(start, end, dirIsX);
// Add the end-point segments
segments = segments.concat(endSegments.reverse());
return {
path: pathFromSegments(segments),
obstacles: segments
};
}, {
requiresObstacles: true
})
};
return algorithms;
}(Highcharts));
(function (H) {
/**
* (c) 2017 Highsoft AS
* Authors: Lars A. V. Cabrera
*
* License: www.highcharts.com/license
*/
/**
* Creates an arrow symbol. Like a triangle, except not filled.
* o
* o
* o
* o
* o
* o
* o
* @param {number} x x position of the arrow
* @param {number} y y position of the arrow
* @param {number} w width of the arrow
* @param {number} h height of the arrow
* @return {Array} Path array
*/
H.SVGRenderer.prototype.symbols.arrow = function (x, y, w, h) {
return [
'M', x, y + h / 2,
'L', x + w, y,
'L', x, y + h / 2,
'L', x + w, y + h
];
};
/**
* Creates a half-width arrow symbol. Like a triangle, except not filled.
* o
* o
* o
* o
* o
* @param {number} x x position of the arrow
* @param {number} y y position of the arrow
* @param {number} w width of the arrow
* @param {number} h height of the arrow
* @return {Array} Path array
*/
H.SVGRenderer.prototype.symbols['arrow-half'] = function (x, y, w, h) {
return H.SVGRenderer.prototype.symbols.arrow(x, y, w / 2, h);
};
/**
* Creates a left-oriented triangle.
* o
* ooooooo
* ooooooooooooo
* ooooooo
* o
* @param {number} x x position of the triangle
* @param {number} y y position of the triangle
* @param {number} w width of the triangle
* @param {number} h height of the triangle
* @return {Array} Path array
*/
H.SVGRenderer.prototype.symbols['triangle-left'] = function (x, y, w, h) {
return [
'M', x + w, y,
'L', x, y + h / 2,
'L', x + w, y + h,
'Z'
];
};
/**
* Alias function for triangle-left.
* @param {number} x x position of the arrow
* @param {number} y y position of the arrow
* @param {number} w width of the arrow
* @param {number} h height of the arrow
* @return {Array} Path array
*/
H.SVGRenderer.prototype.symbols['arrow-filled'] =
H.SVGRenderer.prototype.symbols['triangle-left'];
/**
* Creates a half-width, left-oriented triangle.
* o
* oooo
* ooooooo
* oooo
* o
* @param {number} x x position of the triangle
* @param {number} y y position of the triangle
* @param {number} w width of the triangle
* @param {number} h height of the triangle
* @return {Array} Path array
*/
H.SVGRenderer.prototype.symbols['triangle-left-half'] = function (x, y, w, h) {
return H.SVGRenderer.prototype.symbols['triangle-left'](x, y, w / 2, h);
};
/**
* Alias function for triangle-left-half.
* @param {number} x x position of the arrow
* @param {number} y y position of the arrow
* @param {number} w width of the arrow
* @param {number} h height of the arrow
* @return {Array} Path array
*/
H.SVGRenderer.prototype.symbols['arrow-filled-half'] =
H.SVGRenderer.prototype.symbols['triangle-left-half'];
}(Highcharts));
(function (H, pathfinderAlgorithms) {
/**
* (c) 2016 Highsoft AS
* Authors: Øystein Moseng, Lars A. V. Cabrera
*
* License: www.highcharts.com/license
*/
var defined = H.defined,
deg2rad = H.deg2rad,
extend = H.extend,
each = H.each,
addEvent = H.addEvent,
merge = H.merge,
pick = H.pick,
max = Math.max,
min = Math.min;
/*
TODO:
- Test dynamics, hiding/adding/removing/updating chart/series/points/axes
- Test connecting to multiple points
- Add demos/samples
- Document how to write your own algorithms
- Consider adding a Point.pathTo method that wraps creating a connection
and rendering it
*/
// Set default Pathfinder options
extend(H.defaultOptions, {
/**
* The Pathfinder allows you to define connections between any two points,
* represented as lines - optionally with markers for the start and/or end
* points. Multiple algorithms are available for calculating how the
* connecting lines are drawn.
*
* Pathfinder functionality requires Highcharts Gantt to be loaded. In Gantt
* charts, the Pathfinder is used to draw dependencies between tasks.
*
* @product gantt
* @see [dependency](series.gantt.data.dependency)
* @optionparent pathfinder
*/
pathfinder: {
/**
* Enable the pathfinder for this chart. Requires Highcharts Gantt.
*
* @type {boolean}
* @default true
* @since 6.2.0
* @apioption pathfinder.enabled
*/
/**
* Set the default dash style for this chart's Pathfinder connecting
* lines.
*
* @type {string}
* @default solid
* @since 6.2.0
* @apioption pathfinder.dashStyle
*/
/**
* Set the default color for this chart's Pathfinder connecting lines.
* Defaults to the color of the point being connected.
*
* @type {Color}
* @default null
* @since 6.2.0
* @apioption pathfinder.lineColor
*/
/**
* Set the default pathfinder margin to use, in pixels. Some Pathfinder
* algorithms attempt to avoid obstacles, such as other points in the
* chart. These algorithms use this margin to determine how close lines
* can be to an obstacle. The default is to compute this automatically
* from the size of the obstacles in the chart.
*
* To draw connecting lines close to existing points, set this to a low
* number. For more space around existing points, set this number
* higher.
*
* @type {number}
* @default null
* @since 6.2.0
* @apioption pathfinder.algorithmMargin
*/
/**
* Set the default pathfinder algorithm to use for this chart. It is
* possible to define your own algorithms by adding them to the
* Highcharts.Pathfinder.prototype.algorithms object after the chart
* has been created.
*
* The default algorithms are as follows:
*
* straight: Draws a straight line between the connecting points.
* Does not avoid other points when drawing.
*
* simpleConnect: Finds a path between the points using right angles
* only. Takes only starting/ending points into
* account, and will not avoid other points.
*
* fastAvoid: Finds a path between the points using right angles
* only. Will attempt to avoid other points, but its
* focus is performance over accuracy. Works well with
* less dense datasets.
*
* @type {string}
* @default straight
* @since 6.2.0
* @apioption pathfinder.type
*/
type: 'straight',
/**
* Set the default pixel width for this chart's Pathfinder connecting
* lines.
*
* @type {number}
* @default 1
* @since 6.2.0
* @apioption pathfinder.lineWidth
*/
lineWidth: 1,
/**
* Marker options for this chart's Pathfinder connectors.
*
* @type {object}
* @since 6.2.0
* @apioption pathfinder.marker
*/
marker: {
/**
* Set the radius of the pathfinder markers. The default is
* automatically computed based on the algorithmMargin setting.
*
* Setting marker.width and marker.height will override this
* setting.
*
* @type {number}
* @default null
* @since 6.2.0
* @apioption pathfinder.marker.radius
*/
/**
* Set the width of the pathfinder markers. If not supplied, this
* is inferred from the marker radius.
*
* @type {number}
* @default null
* @since 6.2.0
* @apioption pathfinder.marker.width
*/
/**
* Set the height of the pathfinder markers. If not supplied, this
* is inferred from the marker radius.
*
* @type {number}
* @default null
* @since 6.2.0
* @apioption pathfinder.marker.height
*/
/**
* Set the color of the pathfinder markers. By default this is the
* same as the connector color.
*
* @type {Color}
* @default null
* @since 6.2.0
* @apioption pathfinder.marker.color
*/
/**
* Set the line/border color of the pathfinder markers. By default
* this is the same as the marker color.
*
* @type {Color}
* @default null
* @since 6.2.0
* @apioption pathfinder.marker.lineColor
*/
/**
* Enable markers for the connectors.
*/
enabled: false,
/**
* Horizontal alignment of the markers relative to the points.
*/
align: 'center',
/**
* Vertical alignment of the markers relative to the points.
*/
verticalAlign: 'middle',
/**
* Whether or not to draw the markers inside the points.
*/
inside: false,
/**
* Set the line/border width of the pathfinder markers.
*/
lineWidth: 1
},
/**
* Marker options specific to the start markers for this chart's
* Pathfinder connectors. Overrides the generic marker options.
*
* @type {object}
* @since 6.2.0
* @extends pathfinder.marker
* @apioption pathfinder.startMarker
*/
startMarker: {
/**
* Set the symbol of the pathfinder start markers.
*/
symbol: 'diamond'
},
/**
* Marker options specific to the end markers for this chart's
* Pathfinder connectors. Overrides the generic marker options.
*
* @type {object}
* @since 6.2.0
* @extends pathfinder.marker
* @apioption pathfinder.endMarker
*/
endMarker: {
/**
* Set the symbol of the pathfinder end markers.
*/
symbol: 'arrow-filled'
}
}
});
/**
* Override Pathfinder options for a series. Requires Highcharts Gantt or the
* Pathfinder module.
*
* @since 6.2.0
* @extends pathfinder
* @product gantt
* @apioption plotOptions.series.pathfinder
* @excluding enabled,algorithmMargin
*/
/**
* Connect to a point. Requires Highcharts Gantt to be loaded. This option can
* be either a string, referring to the ID of another point, or an object.
*
* @type {string|object}
* @since 6.2.0
* @extends plotOptions.series.pathfinder
* @product gantt
* @apioption series.xrange.data.connect
*/
/**
* The ID of the point to connect to.
*
* @type {string}
* @since 6.2.0
* @product gantt
* @apioption series.xrange.data.connect.to
*/
/**
* Get point bounding box using plotX/plotY and shapeArgs. If using
* graphic.getBBox() directly, the bbox will be affected by animation.
*
* @param {Highcharts.Point} point
* The point to get BB of.
*
* @return {object}
* Result xMax, xMin, yMax, yMin.
*/
function getPointBB(point) {
var shapeArgs = point.shapeArgs,
bb;
// Prefer using shapeArgs (columns)
if (shapeArgs) {
return {
xMin: shapeArgs.x,
xMax: shapeArgs.x + shapeArgs.width,
yMin: shapeArgs.y,
yMax: shapeArgs.y + shapeArgs.height
};
}
// Otherwise use plotX/plotY and bb
bb = point.graphic && point.graphic.getBBox();
return bb ? {
xMin: point.plotX - bb.width / 2,
xMax: point.plotX + bb.width / 2,
yMin: point.plotY - bb.height / 2,
yMax: point.plotY + bb.height / 2
} : null;
}
/**
* Calculate margin to place around obstacles for the pathfinder in pixels.
* Returns a minimum of 1 pixel margin.
*
* @param {Array} obstacles
* Obstacles to calculate margin from.
*
* @return {number}
* The calculated margin in pixels. At least 1.
*/
function calculateObstacleMargin(obstacles) {
var len = obstacles.length,
i = 0,
j,
obstacleDistance,
distances = [],
// Compute smallest distance between two rectangles
distance = function (a, b, bbMargin) {
// Count the distance even if we are slightly off
var margin = pick(bbMargin, 10),
yOverlap = a.yMax + margin > b.yMin - margin &&
a.yMin - margin < b.yMax + margin,
xOverlap = a.xMax + margin > b.xMin - margin &&
a.xMin - margin < b.xMax + margin,
xDistance = yOverlap ? (
a.xMin > b.xMax ? a.xMin - b.xMax : b.xMin - a.xMax
) : Infinity,
yDistance = xOverlap ? (
a.yMin > b.yMax ? a.yMin - b.yMax : b.yMin - a.yMax
) : Infinity;
// If the rectangles collide, try recomputing with smaller margin.
// If they collide anyway, discard the obstacle.
if (xOverlap && yOverlap) {
return (
margin ?
distance(a, b, Math.floor(margin / 2)) :
Infinity
);
}
return min(xDistance, yDistance);
};
// Go over all obstacles and compare them to the others.
for (; i < len; ++i) {
// Compare to all obstacles ahead. We will already have compared this
// obstacle to the ones before.
for (j = i + 1; j < len; ++j) {
obstacleDistance = distance(obstacles[i], obstacles[j]);
// TODO: Magic number 80
if (obstacleDistance < 80) { // Ignore large distances
distances.push(obstacleDistance);
}
}
}
// Ensure we always have at least one value, even in very spaceous charts
distances.push(80);
return max(
Math.floor(
distances.sort(function (a, b) {
return a - b;
})[
// Discard first 10% of the relevant distances, and then grab
// the smallest one.
Math.floor(distances.length / 10)
] / 2 - 1 // Divide the distance by 2 and subtract 1.
),
1 // 1 is the minimum margin
);
}
/**
* The Connection class. Used internally to represent a connection between two
* points.
*
* @private
* @class Connection
*
* @param {Highcharts.Point} from
* Connection runs from this Point.
*
* @param {Highcharts.Point} to
* Connection runs to this Point.
*
* @param {object} [options]
* Connection options.
*/
function Connection(from, to, options) {
this.init(from, to, options);
}
Connection.prototype = {
/**
* Initialize the Connection object. Used as constructor only.
*
* @function Highcharts.Connection#init
*
* @param {Highcharts.Point} from
* Connection runs from this Point.
*
* @param {Highcharts.Point} to
* Connection runs to this Point.
*
* @param {object} [options]
* Connection options.
*
* @return {void}
*/
init: function (from, to, options) {
this.fromPoint = from;
this.toPoint = to;
this.options = options;
this.chart = from.series.chart;
this.pathfinder = this.chart.pathfinder;
},
/**
* Add (or update) this connection's path on chart. Stores reference to the
* created element on this.graphics.path.
*
* @function Highcharts.Connection#renderPath
*
* @param {Array} path
* Path to render, in array format. E.g. ['M', 0, 0, 'L', 10, 10]
*
* @param {object} [attribs]
* SVG attributes for the path.
*
* @param {object} [animation]
* Animation options for the rendering.
*
* @param {Function} [complete]
* Callback function when the path has been rendered and animation
* is complete.
*
* @return {void}
*/
renderPath: function (path, attribs, animation) {
var connection = this,
chart = this.chart,
pathfinder = chart.pathfinder,
animate = !chart.options.chart.forExport && animation !== false,
pathGraphic = connection.graphics && connection.graphics.path;
// Add the SVG element of the pathfinder group if it doesn't exist
if (!pathfinder.group) {
pathfinder.group = chart.renderer.g()
.addClass('highcharts-pathfinder-group')
.attr({ zIndex: -1 })
.add(chart.seriesGroup);
}
// Shift the group to compensate for plot area.
// Note: Do this always (even when redrawing a path) to avoid issues
// when updating chart in a way that changes plot metrics.
pathfinder.group.translate(chart.plotLeft, chart.plotTop);
// Create path if does not exist
if (!(pathGraphic && pathGraphic.renderer)) {
pathGraphic = chart.renderer.path()
.add(pathfinder.group);
}
// Set path attribs and animate to the new path
pathGraphic.attr(attribs);
pathGraphic[animate ? 'animate' : 'attr']({
d: path
}, animation);
// Store reference on connection
this.graphics = this.graphics || {};
this.graphics.path = pathGraphic;
},
/**
* Calculate and add marker graphics for connection to the chart. The
* created/updated elements are stored on this.graphics.start and
* this.graphics.end.
*
* @function Highcharts.Connection#addMarker
*
* @param {string} type
* Marker type, either 'start' or 'end'.
*
* @param {object} options
* All options for this marker. Not calculated or merged with other
* options.
*
* @param {Array} path
* Connection path in array format. This is used to calculate the
* rotation angle of the markers.
*
* @return {void}
*/
addMarker: function (type, options, path) {
var connection = this,
chart = connection.fromPoint.series.chart,
pathfinder = chart.pathfinder,
renderer = chart.renderer,
point = (
type === 'start' ?
connection.fromPoint :
connection.toPoint
),
anchor = point.getPathfinderAnchorPoint(options),
markerVector,
radians,
rotation,
box,
width,
height,
pathVector;
if (!options.enabled) {
return;
}
// Last vector before start/end of path, used to get angle
if (type === 'start') {
pathVector = {
x: path[4],
y: path[5]
};
} else { // 'end'
pathVector = {
x: path[path.length - 5],
y: path[path.length - 4]
};
}
// Get angle between pathVector and anchor point and use it to create
// marker position.
radians = point.getRadiansToVector(pathVector, anchor);
markerVector = point.getMarkerVector(
radians,
options.radius,
anchor
);
// Rotation of marker is calculated from angle between pathVector and
// markerVector.
// (Note:
// Used to recalculate radians between markerVector and pathVector,
// but this should be the same as between pathVector and anchor.)
rotation = -radians / deg2rad;
if (options.width && options.height) {
width = options.width;
height = options.height;
} else {
width = height = options.radius * 2;
}
// Add graphics object if it does not exist
connection.graphics = connection.graphics || {};
box = {
x: markerVector.x - (width / 2),
y: markerVector.y - (height / 2),
width: width,
height: height,
rotation: rotation,
rotationOriginX: markerVector.x,
rotationOriginY: markerVector.y
};
if (!connection.graphics[type]) {
// Create new marker element
connection.graphics[type] = renderer.symbol(
options.symbol
)
.addClass(
'highcharts-point-connecting-path-' + type + '-marker'
)
.attr(box)
.add(pathfinder.group);
} else {
connection.graphics[type].animate(box);
}
},
/**
* Calculate and return connection path.
* Note: Recalculates chart obstacles on demand if they aren't calculated.
*
* @function Highcharts.Connection#getPath
*
* @param {object} options
* Pathfinder options. Not calculated or merged with other options.
*
* @return {Array}
* Calculated SVG path data in array format.
*/
getPath: function (options) {
var pathfinder = this.pathfinder,
chart = this.chart,
algorithm = pathfinder.algorithms[options.type],
chartObstacles = pathfinder.chartObstacles;
if (typeof algorithm !== 'function') {
H.error(
'"' + options.type + '" is not a Pathfinder algorithm.'
);
return;
}
// This function calculates obstacles on demand if they don't exist
if (algorithm.requiresObstacles && !chartObstacles) {
chartObstacles =
pathfinder.chartObstacles =
pathfinder.getChartObstacles(options);
// If the algorithmMargin was computed, store the result in default
// options.
chart.options.pathfinder.algorithmMargin = options.algorithmMargin;
// Cache some metrics too
pathfinder.chartObstacleMetrics =
pathfinder.getObstacleMetrics(chartObstacles);
}
// Get the SVG path
return algorithm(
// From
this.fromPoint.getPathfinderAnchorPoint(options.startMarker),
// To
this.toPoint.getPathfinderAnchorPoint(options.endMarker),
merge({
chartObstacles: chartObstacles,
lineObstacles: pathfinder.lineObstacles || [],
obstacleMetrics: pathfinder.chartObstacleMetrics,
hardBounds: {
xMin: 0,
xMax: chart.plotWidth,
yMin: 0,
yMax: chart.plotHeight
},
obstacleOptions: {
margin: options.algorithmMargin
},
startDirectionX: pathfinder.getAlgorithmStartDirection(
options.startMarker
)
}, options)
);
},
/**
* (re)Calculate and (re)draw the connection.
*
* @function Highcharts.Connection#render
*/
render: function () {
var connection = this,
fromPoint = connection.fromPoint,
series = fromPoint.series,
chart = series.chart,
pathfinder = chart.pathfinder,
pathResult,
path,
options = merge(
chart.options.pathfinder, series.options.pathfinder,
fromPoint.options.pathfinder, connection.options
),
attribs = {};
// Set path attribs
attribs.class = 'highcharts-point-connecting-path ' +
'highcharts-color-' + fromPoint.colorIndex;
options = merge(attribs, options);
// Set common marker options
if (!defined(options.marker.radius)) {
options.marker.radius = min(max(
Math.ceil((options.algorithmMargin || 8) / 2) - 1, 1
), 5);
}
// Get the path
pathResult = connection.getPath(options);
path = pathResult.path;
// Always update obstacle storage with obstacles from this path.
// We don't know if future calls will need this for their algorithm.
if (pathResult.obstacles) {
pathfinder.lineObstacles = pathfinder.lineObstacles || [];
pathfinder.lineObstacles =
pathfinder.lineObstacles.concat(pathResult.obstacles);
}
// Add the calculated path to the pathfinder group
connection.renderPath(path, attribs, series.options.animation);
// Render the markers
connection.addMarker(
'start',
merge(options.marker, options.startMarker),
path
);
connection.addMarker(
'end',
merge(options.marker, options.endMarker),
path
);
},
/**
* Destroy connection by destroying the added graphics elements.
*
* @function Highcharts.Connection#destroy
*/
destroy: function () {
if (this.graphics) {
H.objectEach(this.graphics, function (val) {
val.destroy();
});
delete this.graphics;
}
}
};
/**
* The Pathfinder class.
*
* @private
* @class Pathfinder
*
* @param {Highcharts.Chart} chart
* The chart to operate on.
*/
function Pathfinder(chart) {
this.init(chart);
}
Pathfinder.prototype = {
algorithms: pathfinderAlgorithms,
/**
* Initialize the Pathfinder object.
*
* @function Highcharts.Pathfinder#init
*
* @param {Highcharts.Chart} chart
* The chart context.
*
* @return {void}
*/
init: function (chart) {
// Initialize pathfinder with chart context
this.chart = chart;
// Init connection reference list
this.connections = [];
// Recalculate paths/obstacles on chart redraw
addEvent(chart, 'redraw', function () {
this.pathfinder.update();
});
},
/**
* Update Pathfinder connections from scratch.
*
* @function Highcharts.Pathfinder#update
*
* @param {boolean} deferRender Whether or not to defer rendering of
* connections until series.afterAnimate event has fired. Used on first
* render.
*/
update: function (deferRender) {
var chart = this.chart,
pathfinder = this,
oldConnections = pathfinder.connections;
// Rebuild pathfinder connections from options
pathfinder.connections = [];
each(chart.series, function (series) {
if (series.visible) {
each(series.points, function (point) {
var to,
connects = (
point.options &&
point.options.connect &&
H.splat(point.options.connect)
);
if (point.visible && point.isInside !== false && connects) {
each(connects, function (connect) {
to = chart.get(typeof connect === 'string' ?
connect : connect.to
);
if (
to instanceof H.Point &&
to.series.visible &&
to.visible &&
to.isInside !== false
) {
// Add new connection
pathfinder.connections.push(new Connection(
point, // from
to,
typeof connect === 'string' ? {} : connect
));
}
});
}
});
}
});
// Clear connections that should not be updated, and move old info over
// to new connections.
for (
var j = 0, k, found, lenOld = oldConnections.length,
lenNew = pathfinder.connections.length;
j < lenOld;
++j
) {
found = false;
for (k = 0; k < lenNew; ++k) {
if (
oldConnections[j].fromPoint ===
pathfinder.connections[k].fromPoint &&
oldConnections[j].toPoint ===
pathfinder.connections[k].toPoint
) {
pathfinder.connections[k].graphics =
oldConnections[j].graphics;
found = true;
break;
}
}
if (!found) {
oldConnections[j].destroy();
}
}
// Clear obstacles to force recalculation. This must be done on every
// redraw in case positions have changed. Recalculation is handled in
// Connection.getPath on demand.
delete this.chartObstacles;
delete this.lineObstacles;
// Draw the pending connections
pathfinder.renderConnections(deferRender);
},
/**
* Draw the chart's connecting paths.
*
* @function Highcharts.Pathfinder#renderConnections
*
* @param {boolean} deferRender Whether or not to defer render until series
* animation is finished. Used on first render.
*/
renderConnections: function (deferRender) {
if (deferRender) {
// Render after series are done animating
each(this.chart.series, function (series) {
var render = function () {
// Find pathfinder connections belonging to this series
// that haven't rendered, and render them now.
var pathfinder = series.chart.pathfinder,
conns = pathfinder && pathfinder.connections || [];
each(conns, function (connection) {
if (
connection.fromPoint &&
connection.fromPoint.series === series
) {
connection.render();
}
});
if (series.pathfinderRemoveRenderEvent) {
series.pathfinderRemoveRenderEvent();
delete series.pathfinderRemoveRenderEvent;
}
};
if (series.options.animation === false) {
render();
} else {
series.pathfinderRemoveRenderEvent = addEvent(
series, 'afterAnimate', render
);
}
});
} else {
// Go through connections and render them
each(this.connections, function (connection) {
connection.render();
});
}
},
/**
* Get obstacles for the points in the chart. Does not include connecting
* lines from Pathfinder. Applies algorithmMargin to the obstacles.
*
* @function Highcharts.Pathfinder#getChartObstacles
*
* @param {object} options
* Options for the calculation. Currenlty only
* options.algorithmMargin.
*
* @return {Array}
* An array of calculated obstacles. Each obstacle is defined as
* an object with xMin, xMax, yMin and yMax properties.
*/
getChartObstacles: function (options) {
var obstacles = [],
series = this.chart.series,
margin = pick(options.algorithmMargin, 0),
calculatedMargin;
for (var i = 0, sLen = series.length; i < sLen; ++i) {
if (series[i].visible) {
for (
var j = 0, pLen = series[i].points.length, bb, point;
j < pLen;
++j
) {
point = series[i].points[j];
if (point.visible) {
bb = getPointBB(point);
if (bb) {
obstacles.push({
xMin: bb.xMin - margin,
xMax: bb.xMax + margin,
yMin: bb.yMin - margin,
yMax: bb.yMax + margin
});
}
}
}
}
}
// Sort obstacles by xMin for optimization
obstacles = obstacles.sort(function (a, b) {
return a.xMin - b.xMin;
});
// Add auto-calculated margin if the option is not defined
if (!defined(options.algorithmMargin)) {
calculatedMargin =
options.algorithmMargin =
calculateObstacleMargin(obstacles);
each(obstacles, function (obstacle) {
obstacle.xMin -= calculatedMargin;
obstacle.xMax += calculatedMargin;
obstacle.yMin -= calculatedMargin;
obstacle.yMax += calculatedMargin;
});
}
return obstacles;
},
/**
* Utility function to get metrics for obstacles:
* - Widest obstacle width
* - Tallest obstacle height
*
* @function Highcharts.Pathfinder#getObstacleMetrics
*
* @param {Array} obstacles
* An array of obstacles to inspect.
*
* @return {object}
* The calculated metrics, as an object with maxHeight and maxWidth
* properties.
*/
getObstacleMetrics: function (obstacles) {
var maxWidth = 0,
maxHeight = 0,
width,
height,
i = obstacles.length;
while (i--) {
width = obstacles[i].xMax - obstacles[i].xMin;
height = obstacles[i].yMax - obstacles[i].yMin;
if (maxWidth < width) {
maxWidth = width;
}
if (maxHeight < height) {
maxHeight = height;
}
}
return {
maxHeight: maxHeight,
maxWidth: maxWidth
};
},
/**
* Utility to get which direction to start the pathfinding algorithm
* (X vs Y), calculated from a set of marker options.
*
* @function Highcharts.Pathfinder#getAlgorithmStartDirection
*
* @param {object} markerOptions
* Marker options to calculate from.
*
* @return {boolean}
* Returns true for X, false for Y, and undefined for
* autocalculate.
*/
getAlgorithmStartDirection: function (markerOptions) {
var xCenter = markerOptions.align !== 'left' &&
markerOptions.align !== 'right',
yCenter = markerOptions.verticalAlign !== 'top' &&
markerOptions.verticalAlign !== 'bottom',
undef;
return xCenter ?
(yCenter ? undef : false) : // x is centered
(yCenter ? true : undef); // x is off-center
}
};
// Add to Highcharts namespace
H.Connection = Connection;
H.Pathfinder = Pathfinder;
// Add pathfinding capabilities to Points
extend(H.Point.prototype, /** @lends Point.prototype */ {
/**
* Get coordinates of anchor point for pathfinder connection.
*
* @private
* @function Highcharts.Point#getPathfinderAnchorPoint
*
* @param {object} markerOptions
* Connection options for position on point.
*
* @return {object}
* An object with x/y properties for the position. Coordinates are
* in plot values, not relative to point.
*/
getPathfinderAnchorPoint: function (markerOptions) {
var bb = getPointBB(this),
x,
y;
switch (markerOptions.align) { // eslint-disable-line default-case
case 'right':
x = 'xMax';
break;
case 'left':
x = 'xMin';
}
switch (markerOptions.verticalAlign) { // eslint-disable-line default-case
case 'top':
y = 'yMin';
break;
case 'bottom':
y = 'yMax';
}
return {
x: x ? bb[x] : (bb.xMin + bb.xMax) / 2,
y: y ? bb[y] : (bb.yMin + bb.yMax) / 2
};
},
/**
* Utility to get the angle from one point to another.
*
* @private
* @function Highcharts.Point#getRadiansToVector
*
* @param {object} v1
* The first vector, as an object with x/y properties.
*
* @param {object} v2
* The second vector, as an object with x/y properties.
*
* @return {number}
* The angle in degrees
*/
getRadiansToVector: function (v1, v2) {
var box;
if (!defined(v2)) {
box = getPointBB(this);
v2 = {
x: (box.xMin + box.xMax) / 2,
y: (box.yMin + box.yMax) / 2
};
}
return Math.atan2(v2.y - v1.y, v1.x - v2.x);
},
/**
* Utility to get the position of the marker, based on the path angle and
* the marker's radius.
*
* @private
* @function Highcharts.Point#getMarkerVector
*
* @param {number} radians
* The angle in radians from the point center to another vector.
*
* @param {number} markerRadius
* The radius of the marker, to calculate the additional distance
* to the center of the marker.
*
* @param {object} anchor
* The anchor point of the path and marker as an object with x/y
* properties.
*
* @return {object}
* The marker vector as an object with x/y properties.
*/
getMarkerVector: function (radians, markerRadius, anchor) {
var twoPI = Math.PI * 2.0,
theta = radians,
bb = getPointBB(this),
rectWidth = bb.xMax - bb.xMin,
rectHeight = bb.yMax - bb.yMin,
rAtan = Math.atan2(rectHeight, rectWidth),
tanTheta = 1,
leftOrRightRegion = false,
rectHalfWidth = rectWidth / 2.0,
rectHalfHeight = rectHeight / 2.0,
rectHorizontalCenter = bb.xMin + rectHalfWidth,
rectVerticalCenter = bb.yMin + rectHalfHeight,
edgePoint = {
x: rectHorizontalCenter,
y: rectVerticalCenter
},
markerPoint = {},
xFactor = 1,
yFactor = 1;
while (theta < -Math.PI) {
theta += twoPI;
}
while (theta > Math.PI) {
theta -= twoPI;
}
tanTheta = Math.tan(theta);
if ((theta > -rAtan) && (theta <= rAtan)) {
// Right side
yFactor = -1;
leftOrRightRegion = true;
} else if (theta > rAtan && theta <= (Math.PI - rAtan)) {
// Top side
yFactor = -1;
} else if (theta > (Math.PI - rAtan) || theta <= -(Math.PI - rAtan)) {
// Left side
xFactor = -1;
leftOrRightRegion = true;
} else {
// Bottom side
xFactor = -1;
}
// Correct the edgePoint according to the placement of the marker
if (leftOrRightRegion) {
edgePoint.x += xFactor * (rectHalfWidth);
edgePoint.y += yFactor * (rectHalfWidth) * tanTheta;
} else {
edgePoint.x += xFactor * (rectHeight / (2.0 * tanTheta));
edgePoint.y += yFactor * (rectHalfHeight);
}
if (anchor.x !== rectHorizontalCenter) {
edgePoint.x = anchor.x;
}
if (anchor.y !== rectVerticalCenter) {
edgePoint.y = anchor.y;
}
markerPoint.x = edgePoint.x + (markerRadius * Math.cos(theta));
markerPoint.y = edgePoint.y - (markerRadius * Math.sin(theta));
return markerPoint;
}
});
// Initialize Pathfinder for charts
H.Chart.prototype.callbacks.push(function (chart) {
var options = chart.options;
if (options.pathfinder.enabled !== false) {
this.pathfinder = new Pathfinder(this);
this.pathfinder.update(true); // First draw, defer render
}
});
}(Highcharts, algorithms));
return (function () {
}());
}));