All files DPolygon.ts

92.85% Statements 715/770
90.49% Branches 219/242
96.72% Functions 177/183
92.68% Lines 659/711

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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  11x 11x 11x 11x 11x   11x 11x                                               11x   11x 11x 11x 11x       11x 6x 6x 6x 6x               11x 17247x 1010x 216x   794x 13459x 13459x       794x 794x 13459x 13459x 13459x   13459x 7854x   5605x         794x 794x   794x   794x 272x 522x 522x         794x     11x   7341x 7341x 7341x   7341x         11x         11x         11x                                             20x                         1x 1x               1x 1x 1x 1x 12x 7x   12x 8x 8x 4x 4x 4x       1x               3x 3x 1x   2x 1x   1x       173x 173x 173x 170x 170x 170x   224x 1276x 170x 40x   170x   173x 2x 2x 2x 7x   173x 1x     173x       8x       460x       20x       950684x       106580x       106900x       73849x       105213x           2x 2x 6x 6x         6x   7x             4x             7x             7x             1x             1x             12x 12x                         5x 5x             8x 8x             3x             4x 4x             3x             1314741x             9x             1x             28x 28x 146x   28x             2x 2x 7x   2x             19x 19x 75x   19x       3x 3x 18x 18x 165x 165x 15x   150x   3x     3x 3x 3x 15x 15x 7x   8x 8x 8x       3x 3x             967x 967x 967x 12330x 12330x 12330x 12330x 202118x 202118x 202118x 202118x   3085x   118x 118x 118x 118x       967x 11910x 11910x 419x 420x 420x 420x 418x 5877x 418x 2x 2x           967x             3x             13879x             16x             6279x             4x 4x 4x 4x 12x 12x 12x 12x 12x 12x 36x 36x 36x 20x 20x   36x 72x 72x 72x 24x 24x 24x       12x     12x 12x 12x 12x           12x 4x 4x     4x             6x 6x 6x 5x   6x 6x 11x 11x 11x 11x 11x 5x   6x     6x 6x 6x 7x 7x 7x 15x 15x 15x 15x 15x 1x     7x   6x 5x   6x                     347x 347x   4048x   347x             32x 26x   6x             213x 213x 213x           177848x                 372x 372x 5739x 5739x 152x     372x               1x         11x 11x             243x 237x 237x 9x     2261x     19x                 1x 1x           488x 488x 488x           4782x       4x 4x       943312x 943312x       13950x       23412x       1516x       1x       1450x 1450x 1450x       3x 14x 1x         19629x             4631x 4631x 3092x   4631x             1362x 1362x 1338x   1362x       1x 2x 1x               1028x       55395x 5912x 5912x     5912x               585x 1x   584x 38x   546x     47x                     596x 596x     596x 1659x   357x   1302x   239x             6x 11x                     18x       397x       722x               2x 2x 2x 2x 8x 6x 2x               48388x                                                                                                                   520x 520x 166x   354x 354x 16x   338x 338x 338x 4885x 4885x 4885x   4885x 2757x   2128x         338x   338x   338x 139x 199x 198x   1x               358x 358x 357x 4999x 357x 12x   345x 4934x 4934x 6x       340x             1304x 1304x 1304x 1304x             28x 293x 293x 293x 5x 5x     28x                     1x   2x                                                                                           60x 44x   2x 4x 4x 2x   2x   4x     13x 13x                   13x 2x 2x         11x       13x       18x   18x 20x 112x   8x   20x     1x 7x 2x     4x 6x       6x     1x 2x 2x         16x 53x                 1982x       266x                   269x 263x       15x       6x                       6x 6x 6x 6x 48x 48x 5x 5x 43x 33x 33x 33x 66x 33x 33x 33x 12x 12x   33x     10x     6x       12x 12x 4725x 224x   4725x 4724x   4725x         16246x 8003x   8243x 3521x   4722x 1x   4721x               1x   1x 1x 1x 10x 10x 5x     1x         77x 77x 77x     77x 21x   56x             13x       13x       5x 5x 16x 5x 16x 73x 15x   58x 58x 3x 2x       5x   5x                 14x   14x 2x   12x 2x   10x 238x 238x 238x     238x   237x     10x 92x 187x 187x 187x 187x 91x 91x           95x         10x 10x 7x         7x 51x 5x 5x   46x     10x 10x 92x 91x 91x     9x 9x             7x 133x 133x 133x     133x   133x     7x 61x 128x 128x 128x 128x 61x 61x           67x         7x 7x 7x 68x   7x 3x 12x     7x   7x 3x         3x 5x 3x 3x   2x     7x 7x 61x 61x 61x     21x 7x       6263x                 6x 6x 6x       908x                                                         605x 605x               4x 4x 44x   4x       2x 2x 2x 2x 2x   6x 6x 6x     2x                               3127x   3127x 3127x 46936x 46936x 46936x           110x 44x   66x 88x     66x 66x       48388x 48388x       48136x 48136x       196x 196x 196x 196x 196x 367x 367x 147x 147x     196x 89x 89x 89x 89x   107x                         103x 103x 103x 103x 103x 13x 90x 77x 13x 13x           103x 103x 103x 103x 102x   981x 981x 981x 981x 351x 250x 250x 75x       630x   981x       102x 63x 132x 327x 3x 3x 6x 3x   324x       132x 3x       174x 102x 157x 287x 36x   251x 130x 14x 55x       157x 41x     102x 3x   99x 41x   116x     1x      
/* eslint-disable max-lines */
import {DCoord, DPoint, LatLng, XYZ} from './DPoint';
import {DLine} from './DLine';
import {DCircle} from './DCircle';
import {DNumbers} from './DNumbers';
import {io as jstsIo, geom, operation} from 'jsts';
import Geometry = geom.Geometry;
import {DPolygonLoop} from './DPolygonLoop';
import {DGeo, isDefAndNotNull, True} from './utils';
import {
  GeometryCollection,
  LineString,
  MultiLineString,
  MultiPoint,
  MultiPolygon,
  Polygon,
  Geometry as GeoJsonGeometry,
  Feature,
  FeatureCollection
} from 'geojson';
 
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface DeepArray<T> extends Array<T | DeepArray<T>> { }
 
const {
  buffer: {
    BufferParameters: {
      CAP_ROUND,
      CAP_FLAT,
      CAP_SQUARE
    }
  }
} = operation;
 
export const MIN_POINTS_IN_VALID_POLYGON = 3;
const APPROXIMATION_VALUE = 0.1;
const MAX_CONVEX_ITERATIONS = 100;
const CLOSE_TO_INTERSECTION_DISTANCE = 0.001;
 
type SetterFunction<T> = (t: DPolygon) => T;
 
const triangleCenter = (triangle: DPolygon): DPoint => {
  const p0 = triangle.at(0);
  const p1 = triangle.at(1);
  const p2 = triangle.at(2);
  return new DPoint((p0.x + p1.x + p2.x) / 3, (p0.y + p1.y + p2.y) / 3);
};
 
/**
 * @ignore
 * @param poly
 * @param p
 */
const containCalculator = (poly: DPolygon, p: DPoint): boolean => {
  const hasSamePoint = poly.points.some((point: DPoint) => point.equal(p));
  if (hasSamePoint) {
    return true;
  }
  for (const [, , polygonLine] of poly.loopPointsGenerator(true)()) {
    const onBorder = polygonLine.x(p).equal(p) && polygonLine.inRange(p);
    Iif (onBorder) {
      return true;
    }
  }
  let totalFi = 0;
  for (const [{x, y}, {x: a, y: b}] of poly.loopPointsGenerator()()) {
    const line1 = new DLine(x - p.x, y - p.y, 0);
    const line2 = new DLine(a - p.x, b - p.y, 0);
    const fiDif = line1.findFi(line2);
 
    if (line1.vectorProduct(line2).c > 0) {
      totalFi += fiDif;
    } else {
      totalFi -= fiDif;
    }
  }
 
  // eslint-disable-next-line no-magic-numbers
  const eps = Math.PI / 10000;
  let result = false;
 
  const absTotalFi = Math.abs(totalFi);
 
  if (absTotalFi < eps) {
    result = false;
  } else if (Math.abs(2 * Math.PI - absTotalFi) < eps) {
    result = true;
  } else E{
    throw new Error('contains2 faild');
  }
 
  return result;
};
 
export class DPolygon {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  properties: Record<string, any> = {};
  holes: DPolygon[] = [];
  private searchStore: Record<number, Record<number, Record<number | string, boolean>>> = {};
 
  constructor(private pPoints: DPoint[] = []) {}
 
  /**
   * Specifies a round line buffer end cap style.
   */
  static CAP_ROUND: number = CAP_ROUND;
 
  /**
   * Specifies a flat line buffer end cap style.
   */
  static CAP_FLAT: number = CAP_FLAT;
 
  /**
   * Specifies a square line buffer end cap style.
   */
  static CAP_SQUARE: number = CAP_SQUARE;
 
  /**
   * Transform array of triangles to Three.JS vertices
   *
   * ```
   * const geometry = new THREE.BufferGeometry();
   * // create a simple square shape. We duplicate the top left and bottom right
   * // vertices because each vertex needs to appear once per triangle.
   * const vertices = new Float32Array( DPolygon.arrayOfTrianglesToVertices(triangles, 10) );
   *
   * // itemSize = 3 because there are 3 values (components) per vertex
   * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
   * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
   * mesh = new THREE.Mesh( geometry, material );
   *
   * scene.add( mesh );
   * ```
   *
   * @param triangles
   * @param height
   */
  static arrayOfTrianglesToVertices(triangles: DPolygon[], height?: number): number[] {
    return triangles.map((v: DPolygon) => (isDefAndNotNull(height) ? v
      .loop()
      .height(height!)
      .run() : v)
      .toArrayOfCoords())
      .flat(2);
  }
 
  /**
   * Get size of min area rectangle.
   * @param poly should be `minAreaRectangle`
   */
  static minAreaRectangleSize(poly: DPolygon): DPoint {
    const {first, second, last} = poly.clone().open();
    return new DPoint(first.distance(second), first.distance(last));
  }
 
  /**
   * Slice line string to dashes.
   * @param poly should be `divideToPieces` at first
   */
  static toDash(poly: DPolygon): DPolygon[] {
    let p = new DPolygon();
    const result = [p];
    let trigger = true;
    for (const point of poly.points) {
      if (trigger) {
        p.push(point.clone());
      }
      if (point.properties.pieceBorder) {
        trigger = !trigger;
        if (trigger) {
          p = new DPolygon();
          result.push(p);
          p.push(point.clone());
        }
      }
    }
    return result;
  }
 
  /**
   * Get min area rectangle direction
   * @param poly should be `minAreaRectangle`
   */
  static minAreaRectangleDirection(poly: DPolygon): number {
    const {first, second, last} = poly.clone().open();
    if (!first || !second || !last) {
      return 0;
    }
    if (first.distance(second) > first.distance(last)) {
      return first.findLine(second).getFi();
    }
    return first.findLine(last).getFi();
  }
 
  static parseFromWKT(wkt: string): DPolygon {
    const data = wkt.trim().toUpperCase();
    let res: DPolygon = new DPolygon();
    if (data.indexOf('POLYGON') === 0) {
      const regexp = /POLYGON \(\((?<data>(?:(?!\)\)$).)*?)\)\)$/miu;
      const reg = regexp.exec(data)!;
      const [path, ...holes] = (reg.groups!.data as string)
        .split('), (')
        .map((p: string) => new DPolygon(p.split(', ')
          .map((pares: string) => DPoint.parse(pares.split(' ').map(Number))!)));
      if (holes && holes.length) {
        path.holes = holes;
      }
      res = path;
    }
    if (data.indexOf('LINESTRING') === 0) {
      const regexp = /LINESTRING \((?<data>(?:(?!\)$).)*?)\)$/miu;
      const reg = regexp.exec(data)!;
      res = new DPolygon((reg.groups!.data as string)
        .split(', ').map((t: string) => DPoint.parse(t.split(' ').map(Number))!));
    }
    if (data.indexOf('POINT') === 0) {
      res = new DPolygon([DPoint.parseFromWKT(data)]);
    }
 
    return res!;
  }
 
  static createSquareBySize(size: DPoint): DPolygon {
    return new DPolygon([DPoint.zero(), size.clone().setX(0), size.clone(), size.clone().setY(0)]).close();
  }
 
  loop(): DPolygonLoop {
    return new DPolygonLoop(this);
  }
 
  set points(p: DPoint[]) {
    this.pPoints = p;
  }
 
  get points(): DPoint[] {
    return this.pPoints;
  }
 
  get maxX(): number {
    return this.reduce<number>((a: number, r: DPoint) => Math.max(a, r.x), -Infinity);
  }
 
  get minX(): number {
    return this.reduce<number>((a: number, r: DPoint) => Math.min(a, r.x), Infinity);
  }
 
  get maxY(): number {
    return this.reduce<number>((a: number, r: DPoint) => Math.max(a, r.y), -Infinity);
  }
 
  get minY(): number {
    return this.reduce<number>((a: number, r: DPoint) => Math.min(a, r.y), Infinity);
  }
 
  get innerCenter(): DPoint {
    const {
      center
    } = this;
    return this.toTriangles().map((t) => {
      const c = triangleCenter(t);
      c.properties.score = Math.min(
        c.distance(t.at(0)),
        c.distance(t.at(1)),
        c.distance(t.at(2))
      ) + c.distance(center);
      return c;
    })
      .sort((a, b) => a.properties.score - b.properties.score)[0];
  }
 
  /**
   * Get center coordinates
   */
  get center(): DPoint {
    return this.leftTop.move(this.size.divide(2));
  }
 
  /**
   * Difference between `maxY` and `minY`. Equal `ΔY` (`dY`)
   */
  get h(): number {
    return this.maxY - this.minY;
  }
 
  /**
   * Difference between `maxX` and `minX`. Equal `ΔX` (`dX`)
   */
  get w(): number {
    return this.maxX - this.minX;
  }
 
  /**
   * Difference between `maxY` and `minY`. Equal `height` (`h`)
   */
  get dY(): number {
    return this.h;
  }
 
  /**
   * Difference between `maxX` and `minX`. Equal `width` (`w`)
   */
  get dX(): number {
    return this.w;
  }
 
  /**
   * Get closed extend polygon
   */
  get extend(): DPolygon {
    const {minX, minY, maxX, maxY} = this;
    return new DPolygon([
      new DPoint(minX, minY),
      new DPoint(maxX, minY),
      new DPoint(maxX, maxY),
      new DPoint(minX, maxY),
      new DPoint(minX, minY)
    ]);
  }
 
  /**
   * Point with `width` value as `x` and `height` value as `y`
   */
  get size(): DPoint {
    const {w, h} = this;
    return new DPoint(w, h);
  }
 
  /**
   * Point with minimal `x` and `y`
   */
  get leftTop(): DPoint {
    const {minX, minY} = this;
    return new DPoint(minX, minY);
  }
 
  /**
   * Point with minimal `x` and `y`
   */
  get minPoint(): DPoint {
    return this.leftTop;
  }
 
  /**
   * Point with maximal `x` and `y`
   */
  get rightBottom(): DPoint {
    const {maxX, maxY} = this;
    return new DPoint(maxX, maxY);
  }
 
  /**
   * Point with maximal `x` and `y`
   */
  get maxPoint(): DPoint {
    return this.rightBottom;
  }
 
  /**
   * Next point index
   */
  get length(): number {
    return this.pPoints.length;
  }
 
  /**
   * Get length of line string.
   */
  get fullLength(): number {
    return this.clone().open().perimeter;
  }
 
  /**
   * Get length of line string. For big distances in lat/lon.
   */
  get fullLengthLatLon(): number {
    return this.clone().open().perimeterLatLon;
  }
 
  /**
   * Get perimeter.
   */
  get perimeter(): number {
    let p = 0;
    for (const [p1, p2] of this.loopPointsGenerator()()) {
      p += p1.distance(p2);
    }
    return p;
  }
 
  /**
   * Get perimeter. For big distances in lat/lon.
   */
  get perimeterLatLon(): number {
    let p = 0;
    for (const [p1, p2] of this.loopPointsGenerator()()) {
      p += p1.distanceLatLon(p2);
    }
    return p;
  }
 
  /**
   * Get polygon area
   */
  get area(): number {
    let sum = 0;
    for (const [{x, y}, {x: a, y: b}] of this.deintersection.loopPointsGenerator()()) {
      sum += x * b - y * a;
    }
    return Math.abs(sum / 2) - this.holes.reduce((a: number, hole: DPolygon) => a + hole.area, 0);
  }
 
  get filledDeintersection(): DPolygon {
    const p = this.clone().deintersection.removeDuplicates().clockWise.open();
    const findSameCorners = (startIndex: number = 0): ([number, number] | undefined) => {
      const store: Record<string, number> = {};
      for (let i = startIndex; i < p.length; i++) {
        const key = p.at(i).toString();
        if (typeof store[key] === 'number') {
          return [store[key], i];
        }
        store[key] = i;
      }
      return undefined;
    };
 
    let indexes = findSameCorners();
    const holes = [];
    while (indexes) {
      const a = new DPolygon(p.clone().removePart(indexes[0], indexes[1] - indexes[0]));
      if (a.isClockwise) {
        indexes = findSameCorners(indexes[0] + 1);
      } else {
        holes.push(a.close());
        p.removePart(indexes[0], indexes[1] - indexes[0]);
        indexes = findSameCorners();
      }
    }
 
    p.holes = holes;
    return p.close();
  }
 
  /**
   * Get deintesected polygon.
   */
  get deintersection(): DPolygon {
    let p = this.clone().close();
    const store: Record<string, number[]> = {};
    for (let i = 0; i < p.length - 1; i++) {
      const k = p.at(i).toString();
      store[k] = store[k] || [];
      store[k].push(i);
      for (let j = i + 2; j < p.length - 1; j++) {
        const firstLine = p.at(i).findLine(p.at(i + 1));
        const secondLine = p.at(j).findLine(p.at(j + 1));
        const intersectionPoint = firstLine.intersection(secondLine);
        if (
          intersectionPoint &&
          ![...firstLine.points, ...secondLine.points].some((t: DPoint) => t.like(intersectionPoint))
        ) {
          const part = p.removePart(i, j - i).reverse();
          p.insertAfter(i, ...part);
          p.insertAfter(j, intersectionPoint);
          p.insertAfter(i, intersectionPoint);
        }
      }
    }
    for (const key of Object.keys(store)) {
      const record = store[key];
      if (record.length > 1) {
        for (let j = record.length - 1; j > 0; j--) {
          const origin = p.clone();
          const d = record[j] - record[j - 1];
          if (d > 1) {
            const part = new DPolygon(origin.removePart(record[j - 1], d));
            const allInside = part.reduce((a: boolean, e: DPoint) => a && containCalculator(origin, e), true);
            if (allInside && origin.isClockwise === part.isClockwise) {
              origin.insertAfter(record[j - 1] - 1, ...part.reverse().points);
              p = origin;
            }
          }
        }
      }
    }
    return p;
  }
 
  /**
   * Check if polygon contain more than three points
   */
  get valid(): boolean {
    return this.length > MIN_POINTS_IN_VALID_POLYGON;
  }
 
  /**
   * Get first point
   */
  get first(): DPoint {
    return this.at(0);
  }
 
  /**
   * Get second point
   */
  get second(): DPoint {
    return this.at(1);
  }
 
  /**
   * Get last point
   */
  get last(): DPoint {
    return this.at(this.length - 1);
  }
 
  /**
   * Get min area rectangle
   */
  get minAreaRectangle(): DPolygon {
    const p = this.convex;
    let resultPolygon = new DPolygon();
    let resultArea = Infinity;
    for (const [, , l] of p.loopPointsGenerator(true)()) {
      let maxWidth = 0;
      let maxWidthPoint1: DPoint | null = null;
      let maxWidthPoint2: DPoint | null = null;
      let maxHeight = 0;
      let maxHeightPoint: DPoint | null = null;
      for (const [z, , , i] of p.loopPointsGenerator()()) {
        const p1: DPoint = l.findPoint(l.findPerpendicular(z))!;
        const h = p1.distance(z);
        if (h >= maxHeight) {
          maxHeight = h;
          maxHeightPoint = z;
        }
        for (let j = i; j < p.length - 1; j++) {
          const p2: DPoint = l.findPoint(l.findPerpendicular(p.at(j)))!;
          const w = p1.distance(p2);
          if (w >= maxWidth) {
            maxWidth = w;
            maxWidthPoint1 = p1;
            maxWidthPoint2 = p2;
          }
        }
      }
      Iif (!maxWidthPoint1 || !maxWidthPoint2 || !maxHeightPoint) {
        continue;
      }
      const widthLine = maxWidthPoint1.findLine(maxWidthPoint2);
      const perpendicular1 = widthLine.findPerpendicular(maxWidthPoint1);
      const perpendicular2 = widthLine.findPerpendicular(maxWidthPoint2);
      const tempPolygon = new DPolygon([
        maxWidthPoint1,
        maxWidthPoint2,
        perpendicular2.findPoint(perpendicular2.findPerpendicular(maxHeightPoint))!,
        perpendicular1.findPoint(perpendicular1.findPerpendicular(maxHeightPoint))!
      ]).close();
      if (tempPolygon.area < resultArea) {
        resultPolygon = tempPolygon;
        resultArea = tempPolygon.area;
      }
    }
    return resultPolygon;
  }
 
  /**
   * Get convex polygon
   */
  get convex(): DPolygon {
    let p = this.clone().open();
    const {isClockwise} = p;
    if (!isClockwise) {
      p.reverse();
    }
    let l = 0;
    do {
      const p1 = p.last;
      const p2 = p.first;
      const p3 = p.second;
      const d = p2.findInnerAngle(p1, p3);
      if (d > Math.PI || DNumbers.likeZero(DNumbers.rad2Deg(d)) || DNumbers.likePI(d) || DNumbers.like2PI(d)) {
        p.removePart(-1, 1);
      } else {
        break;
      }
    } while (p.length);
    p.close();
    let iteration = 0;
    do {
      p = p.deintersection;
      l = p.length;
      for (let i = 1; i < p.length - 1; i++) {
        const p1 = p.at(i - 1);
        const p2 = p.at(i);
        const p3 = p.at(i + 1);
        const d = p2.findInnerAngle(p1, p3);
        if (d > Math.PI || DNumbers.likeZero(DNumbers.rad2Deg(d)) || DNumbers.likePI(d) || DNumbers.like2PI(d)) {
          p.removePart(--i, 1);
        }
      }
      iteration++;
    } while (p.length !== l && iteration < MAX_CONVEX_ITERATIONS);
    if (!isClockwise) {
      p.reverse();
    }
    return p;
  }
 
  /**
   * Check polygon direction
   *
   * For normal Cartesian coordinate system. The reason that's worth mentioning is that some common contexts,
   * like HTML5 canvas, use an inverted Y-axis. Then the rule has to be flipped: if the area is negative,
   * the curve is clockwise.
   */
  get isClockwise(): boolean {
    let sum = 0;
    for (const [{x, y}, {x: a, y: b}] of this.clone().close()
      .loopPointsGenerator()()) {
      sum += (a - x) * (b + y);
    }
    return sum < 0;
  }
 
  /**
   * Get clockwise polygon
   */
  get clockWise(): DPolygon {
    if (this.isClockwise) {
      return this.clone();
    }
    return this.clone().reverse();
  }
 
  /**
   * Get polygon clone without holes
   */
  get noHoles(): DPolygon {
    const res = this.clone();
    res.holes = [];
    return res;
  }
 
  reduce<T>(f: (a: T, p: DPoint) => T, v: T): T;
  reduce<T>(f: (a: T, p: DPoint, index: number) => T, v: T): T;
  reduce<T>(f: (a: T, p: DPoint, index: number) => T, v: T): T {
    return this.pPoints.reduce(f, v);
  }
 
  /**
   * Check polygon intersection with line
   * @param l
   * @param [includeOnly=false]
   */
  intersection(l: DLine, includeOnly: boolean = false): DPoint[] {
    const res = [];
    for (const [, , line] of this.loopPointsGenerator(true)()) {
      const intersect = line.intersection(l, 0, includeOnly);
      if (intersect) {
        res.push(intersect);
      }
    }
    return res;
  }
 
  /**
   * Set polygon center
   * @param newCenter
   */
  setCenter(newCenter: DPoint): DPolygon {
    return this.loop()
      .move(newCenter.clone().move(this.center.minus()))
      .run();
  }
 
  static WKT_LINESTRING = 'LINESTRING';
  static WKT_POLYGON = 'POLYGON';
 
  /**
   * @param [type = DPolygon.WKT_POLYGON] Available values `DPolygon.WKT_POLYGON`, `DPolygon.WKT_LINESTRING`
   * @param [withZ = false]
   */
  toWKT(type: string = DPolygon.WKT_POLYGON, withZ: boolean = false): string {
    if (type === DPolygon.WKT_POLYGON) {
      let h = '';
      if (this.holes && this.holes.length) {
        h = `, ${this.holes.map((hole: DPolygon) => hole.toString())
          .join(', ')}`;
      }
      return `POLYGON ((${this.deintersection.mapArray<string>((r: DPoint) => `${r.x} ${r.y}${withZ ? ` ${r.z}` : ''}`)
        .join(', ')})${h})`;
    }
    return `LINESTRING (${this.mapArray<string>((r: DPoint) => `${r.x} ${r.y}${withZ ? ` ${r.z}` : ''}`)
      .join(', ')})`;
  }
 
  /**
   * Filter points
   * @param f
   */
  filter(f: (p: DPoint) => boolean): DPolygon {
    this.pPoints = this.pPoints.filter(f);
    return this;
  }
 
  map(f: (r: DPoint) => DPoint): DPolygon;
  map(f: (r: DPoint, index: number) => DPoint): DPolygon;
  map(f: (r: DPoint, index: number) => DPoint): DPolygon {
    this.pPoints = this.mapArray<DPoint>(f);
    this.holes = this.holes.map((h: DPolygon) => h.map(f));
    return this;
  }
 
  mapArray<T>(f: (r: DPoint) => T): T[];
  mapArray<T>(f: (r: DPoint, index: number) => T): T[];
  mapArray<T>(f: (r: DPoint, index: number) => T): T[] {
    return this.pPoints.map(f);
  }
 
  sort(f: (a: DPoint, b: DPoint) => number): DPolygon {
    this.points.sort(f);
    return this;
  }
 
  at(index: number): DPoint {
    const {length} = this;
    return this.points[(index % length + length) % length];
  }
 
  pop(): DPoint {
    return this.pPoints.pop()!;
  }
 
  push(...args: DPoint[]): number {
    return this.pPoints.push(...args);
  }
 
  shift(): DPoint {
    return this.pPoints.shift()!;
  }
 
  unshift(...args: DPoint[]): number {
    return this.pPoints.unshift(...args);
  }
 
  reverse(): DPolygon {
    this.pPoints = this.pPoints.reverse();
    this.holes = this.holes.map((h: DPolygon) => h.reverse());
    return this;
  }
 
  getValue(): string {
    return (
      this.pPoints.map((r: DPoint) => r.getValue()) + this.holes
        .reduce((a: string, h: DPolygon) => a + h.getValue(), '')
    );
  }
 
  toString(): string {
    return `(${this.mapArray<string>((r: DPoint) => r.toString()).join(', ')})`;
  }
 
  /**
   * Add to the end of polygon point equal to first point if it not exist
   */
  close(): DPolygon {
    const p0 = this.first;
    if (p0 && !this.closed) {
      this.push(p0.clone());
    }
    return this;
  }
 
  /**
   * Remove from the end of polygon point equal to first point if it exist
   */
  open(): DPolygon {
    const p = this.first;
    if (this.length > 2 && p && this.closed) {
      this.pop();
    }
    return this;
  }
 
  add(poly: DPolygon): DPolygon {
    const res = new DPolygon([...this.points, ...poly.points]).close();
    res.holes = [...this.holes, ...poly.holes].map((h: DPolygon) => h.clone());
    return res;
  }
 
  /**
   * Check if has point in list of points
   * @param p
   */
  has(p: DPoint): boolean {
    return this.pPoints.some((q: DPoint) => q.equal(p));
  }
 
  clone(): DPolygon {
    const res = new DPolygon(this.points.map((r: DPoint) => r.clone()));
    res.holes = this.holes.map((h: DPolygon) => h.clone());
    res.properties = {
      ...this.properties
    };
    return res;
  }
 
  /**
   * Check is it fully equal.
   * @param p
   */
  equal(p: DPolygon | null): boolean {
    if (!(p instanceof DPolygon)) {
      return false;
    }
    if (this.length !== p.length || this.holes.length !== p.holes.length) {
      return false;
    }
    return (
      this.same(p) &&
      this.holes.reduce(
        (a: boolean, hole: DPolygon) => a && p.holes.some((pHoles: DPolygon) => pHoles.same(hole)),
        true
      )
    );
  }
 
  /**
   * Check is polygons are same. They can be with different directions and different start points.
   * @param p
   */
  same(p: DPolygon): boolean {
    const pClone = p.clone().close();
    const thisAsString = this.clone()
      .close()
      .toString();
    for (let i = 0; i < pClone.length; i++) {
      if (thisAsString === pClone.toString() || thisAsString === pClone.clone().reverse()
        .toString()) {
        return true;
      }
      pClone.nextStart();
    }
    return false;
  }
 
  findIndex(p: DPoint): number;
  findIndex(f: (p: DPoint) => boolean): number;
  findIndex(f: (p: DPoint, index: number) => boolean): number;
  findIndex(a: ((p: DPoint, index: number) => boolean) | DPoint): number {
    if (a instanceof DPoint) {
      return this.points.findIndex((t: DPoint) => t.equal(a));
    }
    return this.points.findIndex(a);
  }
 
  /**
   * Get polygon approximation by
   * [Ramer–Douglas–Peucker algorithm](https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm)
   * @param [e=Math.sqrt(this.perimeter)*APPROXIMATION_VALUE]
   */
  approximation(e: number = Math.sqrt(this.perimeter) * APPROXIMATION_VALUE): DPolygon {
    return new DPolygon(this.clone().douglasPeucker(this.pPoints, e));
  }
 
  insertAfter(index: number, ...points: DPoint[]): void {
    this.pPoints.splice(index + 1, 0, ...points);
  }
 
  removePart(index: number, count: number): DPoint[] {
    return this.pPoints.splice(index + 1, count);
  }
 
  /**
   * Check intersection with other polygon
   * @param p
   */
  hasSimpleIntersection(p: DPolygon): boolean {
    const extend1 = this.extend;
    const extend2 = p.extend;
    const extend1points = extend1.points;
    const extend2points = extend2.points;
    const in1 = extend1points.some((t: DPoint) => extend2.simpleInclude(t));
    const in2 = extend2points.some((t: DPoint) => extend1.simpleInclude(t));
    return in1 || in2;
  }
 
  /**
   * Check if it possible to include point
   * @param p
   */
  simpleInclude(p: DPoint): boolean {
    return this.simpleIncludeX(p) && this.simpleIncludeY(p);
  }
 
  drawPolygonOnCanvas(
    canvas: HTMLCanvasElement | OffscreenCanvas,
    fillColor?: string,
    strokeColor?: string,
    shadowColor?: string,
    lineWidth: number = 1,
    steps: number = this.length - 1
  ): DPolygon {
    Iif (this.length > 1) {
      const ctx = canvas.getContext('2d')!;
      Iif (fillColor) {
        ctx.fillStyle = fillColor;
      }
      Iif (strokeColor) {
        ctx.strokeStyle = strokeColor;
      }
      Iif (lineWidth) {
        ctx.lineWidth = lineWidth;
      }
      Iif (fillColor || strokeColor) {
        ctx.beginPath();
      }
      this.goByPath(ctx, steps % this.length);
      Iif (shadowColor) {
        ctx.shadowColor = shadowColor;
        ctx.shadowBlur = 0;
        ctx.shadowOffsetX = 1;
        ctx.shadowOffsetY = 1;
      }
      Iif (fillColor) {
        ctx.closePath();
        ctx.fill();
      }
      Iif (strokeColor) {
        ctx.stroke();
      }
    }
    return this;
  }
 
  clearPolygonOnCanvas(canvas: HTMLCanvasElement | OffscreenCanvas): void {
    const ctx = canvas.getContext('2d')!;
    const old = ctx.globalCompositeOperation;
    ctx.globalCompositeOperation = 'destination-out';
    this.goByPath(ctx);
    ctx.fill();
    ctx.globalCompositeOperation = old;
  }
 
  /**
   * Check if contain point
   * @param p
   * @param [isBorderInside=false]
   */
  contain(p: DPoint, isBorderInside: boolean = false): boolean {
    const simpleInclude = this.simpleInclude(p);
    if (!simpleInclude) {
      return false;
    }
    const onBorder = this.onBorder(p);
    if (onBorder) {
      return isBorderInside;
    }
    const poly = this.deintersection;
    let totalFi = 0;
    for (const [{x, y}, {x: a, y: b}] of poly.loopPointsGenerator()()) {
      const line1 = new DLine(x - p.x, y - p.y, 0);
      const line2 = new DLine(a - p.x, b - p.y, 0);
      const fiDif = line1.findFi(line2);
 
      if (line1.vectorProduct(line2).c > 0) {
        totalFi += fiDif;
      } else {
        totalFi -= fiDif;
      }
    }
 
    // eslint-disable-next-line no-magic-numbers
    const eps = Math.PI / 10000;
 
    const absTotalFi = Math.abs(totalFi);
 
    if (absTotalFi < eps) {
      return false;
    } else if (Math.abs(2 * Math.PI - absTotalFi) < eps) {
      return true;
    }
    throw new Error('contains2 faild');
  }
 
  /**
   * Check if point on border
   * @param p
   */
  onBorder(p: DPoint): boolean {
    const simpleInclude = this.simpleInclude(p);
    if (simpleInclude) {
      const poly = this.deintersection;
      const hasSamePoint = this.points.some((point: DPoint) => point.equal(p));
      if (hasSamePoint) {
        return true;
      }
      for (const [, , polygonLine] of poly.loopPointsGenerator(true)()) {
        const onBorder = polygonLine.x(p).equal(p) && polygonLine.inRange(p);
        if (onBorder) {
          return true;
        }
      }
    }
    return false;
  }
 
  /**
   * Change start point to second point
   */
  nextStart(): DPolygon {
    this.open();
    this.push(this.shift());
    this.close();
    return this;
  }
 
  /**
   * Remove duplicates points
   */
  removeDuplicates(): DPolygon {
    for (let i = 0; i < this.length - 1; i++) {
      const p1 = this.at(i);
      const p2 = this.at(i + 1);
      if (p1.equal(p2)) {
        this.removePart(i, 1);
        i--;
      }
    }
    return this;
  }
 
  /**
   * @param polygons
   * @param [format='xyz'] Default value `DGeo.parseFormat`
   */
  static toGeoJSONFeatureCollection(
    polygons: DPolygon[],
    format: string = DGeo.parseFormat
  ): FeatureCollection<LineString | Polygon> {
    return {
      type: 'FeatureCollection',
      features: polygons.map((polygon) => polygon.toGeoJSONFeature(format))
    };
  }
 
  /**
   * Parse from [OpenLayers](https://openlayers.org/) coordinates
   * @param a
   * @param [format='xyz'] Default value `DGeo.parseFormat`
   */
  static parse(a: LatLng[], format?: string): DPolygon;
 
  /**
   * Parse from [GeoJSON](https://en.wikipedia.org/wiki/GeoJSON) coordinates
   * @param a
   * @param [format='xyz'] Default value `DGeo.parseFormat`
   */
  static parse(a: number[][], format?: string): DPolygon;
 
  /**
   * Parse from [OpenLayers](https://openlayers.org/) coordinates
   * @param a
   * @param [format='xyz'] Default value `DGeo.parseFormat`
   */
  static parse(a: DCoord[], format?: string): DPolygon;
 
  /**
   * Parse from [OpenLayers](https://openlayers.org/) coordinates
   * @param a
   * @param [format='xyz'] Default value `DGeo.parseFormat`
   */
  static parse(a: XYZ[], format?: string): DPolygon;
 
  /**
   * Parse from GeoJSON
   * @param a
   * @param [format='xyz'] Default value `DGeo.parseFormat`
   */
  static parse(
    a: GeoJsonGeometry | Feature | FeatureCollection<LineString | Polygon>,
    format?: string
  ): DPolygon | DeepArray<DPolygon>;
 
  static parse(
    a: XYZ[] | LatLng[] | number[][] | DCoord[] | GeoJsonGeometry | Feature | FeatureCollection<LineString | Polygon>,
    format: string = DGeo.parseFormat
  ): DPolygon | DeepArray<DPolygon> {
    if ((a as GeoJsonGeometry).type) {
      switch ((a as GeoJsonGeometry | Feature | FeatureCollection).type) {
        case 'FeatureCollection':
          return (a as FeatureCollection).features.reduce((ak: DPolygon[], f) => {
            const t = DPolygon.parse(f, format);
            if (Array.isArray(t)) {
              ak.push(...(t as DPolygon[]));
            } else {
              ak.push(t);
            }
            return ak;
          }, []);
        case 'Feature': {
          const t = DPolygon.parse((a as Feature).geometry, format) as DPolygon;
          const props = {
            ...(a as Feature).properties,
            ...(
              (a as Feature).id ? (
                {
                  id: (a as Feature).id
                }
              ) : ({})
            )
          };
          if (Array.isArray(t)) {
            t.forEach((record) => {
              record.properties = {
                ...props
              };
            });
          } else {
            t.properties = {
              ...props
            };
          }
          return t;
        }
        case 'LineString':
        case 'MultiPoint':
          return new DPolygon((a as MultiPoint).coordinates.map((c) => DPoint.parse(c, format)));
        case 'Polygon':
          return (a as Polygon).coordinates.reduce((ak, line, index) => {
            if (index === 0) {
              ak.points = line.map((c) => DPoint.parse(c, format));
            } else {
              ak.holes.push(new DPolygon(line.map((c) => DPoint.parse(c, format))));
            }
            return ak;
          }, new DPolygon());
        case 'MultiLineString':
          return (a as MultiLineString).coordinates.reduce((ak: DPolygon[], line) => {
            ak.push(new DPolygon(line.map((c) => DPoint.parse(c, format))));
            return ak;
          }, []);
        case 'MultiPolygon':
          return (a as MultiPolygon).coordinates.reduce((ak: DPolygon[], coordinates) => {
            ak.push(DPolygon.parse({
              type: 'Polygon',
              coordinates
            }, format) as DPolygon);
            return ak;
          }, []);
        case 'GeometryCollection':
          return (a as GeometryCollection).geometries.reduce((ak: DeepArray<DPolygon>, line) => {
            ak.push(DPolygon.parse(line, format));
            return ak;
          }, []);
        default:
      }
    }
    return new DPolygon((a as LatLng[] | number[][] | DCoord[] | XYZ[])
      .map((r: LatLng | number[] | DCoord | XYZ) => DPoint.parse(r, format)));
  }
 
  /**
   * Transform to array of coordinates for [OpenLayers](https://openlayers.org/) or
   * [GeoJSON](https://en.wikipedia.org/wiki/GeoJSON)
   * @param [format='xyz'] Default value `DGeo.parseFormat`
   */
  toArrayOfCoords(format: string = DGeo.parseFormat): DCoord[] {
    return this.mapArray((r) => r.toCoords(format));
  }
 
  toGeoJSONFeature(format: string = DGeo.parseFormat): Feature<LineString | Polygon> {
    return {
      type: 'Feature',
      properties: {
        ...this.properties
      },
      geometry: this.toGeoJSON(format)
    };
  }
 
  toGeoJSON(format: string = DGeo.parseFormat): LineString | Polygon {
    if (this.closed) {
      return {
        type: 'Polygon',
        coordinates: [
          this.toArrayOfCoords(format),
          ...this.holes.map((h: DPolygon) => h.toArrayOfCoords(format))
        ]
      }as Polygon;
    }
    return {
      type: 'LineString',
      coordinates: this.toArrayOfCoords(format)
    } as LineString;
  }
 
  /**
   * Divide line string to pieces by length
   * @param piecesCount
   * @param [withAltitude=false]
   */
  divideToPieces(piecesCount: number, withAltitude: boolean = false): DPolygon {
    const {fullLength} = this;
    const pieceLength = fullLength / piecesCount;
    let currentPieceLength = pieceLength;
    for (const [p1, p2, , i] of this.loopPointsGenerator()()) {
      const d = p1.distance(p2);
      if (d === currentPieceLength) {
        p2.properties.pieceBorder = true;
        currentPieceLength = pieceLength;
      } else if (d - currentPieceLength > 0) {
        const circle = new DCircle(p1, currentPieceLength);
        const line = p1.findLine(p2);
        const intersectionPoint: DPoint = (line.intersectionWithCircle(circle) as [DPoint, DPoint])
          .filter((p) => line.inRange(p, CLOSE_TO_INTERSECTION_DISTANCE))[0]!;
        intersectionPoint.properties.pieceBorder = true;
        this.insertAfter(i, intersectionPoint);
        if (withAltitude) {
          const p1z = p1.z!;
          intersectionPoint.z = p1z - (p1z - p2.z!) * (p1.distance(intersectionPoint) / d);
        }
        currentPieceLength = pieceLength;
      } else {
        // If d - currentPieceLength < 0
        currentPieceLength -= d;
      }
    }
    return this;
  }
 
  prepareToFastSearch(): void {
    this.searchStore = {};
    for (const {x, y, z} of this.points) {
      if (!this.searchStore[x]) {
        this.searchStore[x] = {};
      }
      if (!this.searchStore[x][y]) {
        this.searchStore[x][y] = {};
      }
      this.searchStore[x][y][z || 'undefined'] = true;
    }
  }
 
  fastHas({x, y, z}: DPoint): boolean {
    if (!this.searchStore[x]) {
      return false;
    }
    if (!this.searchStore[x][y]) {
      return false;
    }
    if (!this.searchStore[x][y][z || 'undefined']) {
      return false;
    }
    return this.searchStore[x][y][z || 'undefined'];
  }
 
  /**
   * Get line string as line string with growing length. For animation.
   */
  get growingPiecesGenerator(): () => Generator<DPolygon, DPolygon> {
    // eslint-disable-next-line @typescript-eslint/no-this-alias,consistent-this
    const polygon = this;
    // eslint-disable-next-line func-names
    return function *() {
      const r = new DPolygon();
      for (const p of polygon.pPoints) {
        r.push(p);
        if (p.properties.pieceBorder) {
          yield r.clone();
        }
      }
      return r.clone();
    };
  }
 
  simpleUnion(p: DPolygon): DPolygon | null {
    try {
      const res = this.simpleLogicFunction(p, true, true);
      Iif (res === null) {
        return null;
      }
      if (res instanceof DPolygon) {
        return res;
      }
      return null;
    } catch (ex) {
      return null;
    }
  }
 
  simpleIntersection(p: DPolygon): DPolygon | null | DPolygon[] {
    return this.simpleLogicFunction(p, false, false);
  }
 
  simpleDifference(p: DPolygon): DPolygon | null | DPolygon[] {
    return this.simpleLogicFunction(p, true, false);
  }
 
  smartUnion(p: DPolygon): DPolygon | null {
    const res = this.clone().simpleUnion(p);
    if (res) {
      let allHoles = [...this.holes, ...p.holes, ...res.holes].map((h: DPolygon) => h.clone());
      for (const a of allHoles) {
        for (const b of allHoles) {
          if (a.equal(b)) {
            continue;
          }
          const r = a.simpleUnion(b);
          if (r) {
            allHoles = allHoles.filter((v: DPolygon) => !v.equal(a) && !v.equal(b));
            allHoles.push(r);
          }
        }
      }
      res.holes = allHoles;
    }
    return res;
  }
 
  /**
   * Divide polygon to triangles
   *
   * ![Example](https://edejin.github.io/DGeoUtils/media/examples/toTriangles.png)
   */
  toTriangles(): DPolygon[] {
    const q = this.clone().removeDuplicates()
      .open();
    if (q.length < 3) {
      return [];
    }
    if (q.length === 3) {
      return [q];
    }
    const innerAndNotIntersect = (poly: DPolygon, p1: DPoint, p2: DPoint): boolean => {
      const l = p1.findLine(p2);
      const {center} = l;
      const intersections = poly.holes.reduce((a: boolean, hole: DPolygon) => a && Boolean(hole.clone().close()
        .intersection(l, true).length), Boolean(poly.clone().close()
        .intersection(l, true).length));
      const contain = poly.holes.reduce((a: boolean, hole: DPolygon) => a && !hole
        .contain(center), poly.contain(center));
      return !intersections && contain;
    };
 
    const getTriangle = (poly: DPolygon): DPolygon | void => {
      for (let i = 0; i < poly.length; i++) {
        const p0 = poly.at(0);
        const p1 = poly.at(1);
        const p2 = poly.at(2);
        if (innerAndNotIntersect(poly, p0, p2)) {
          poly.removePart(0, 1);
          return new DPolygon([
            p0.clone(),
            p1.clone(),
            p2.clone()
          ]);
        }
        poly.push(poly.shift());
      }
      return undefined;
    };
 
    const p = this.clone().removeDuplicates().clockWise.open();
    while (p.holes.length) {
      const h = p.holes.shift()!
        .clone()
        .clockWise
        .reverse()
        .close();
      for (let i = 0; i < p.length; i++) {
        if (innerAndNotIntersect(p, p.first, h.first)) {
          p.insertAfter(0, ...h.points, p.first);
          break;
        }
        p.push(p.shift());
      }
    }
    const res: DPolygon[] = [];
    while (p.length > 3) {
      const triangle = getTriangle(p);
      if (triangle) {
        res.push(triangle);
      }
    }
    res.push(p);
    return res;
  }
 
  /**
   * Divide polygon to triangles and return points indexes
   */
  getTrianglesPointIndexes(): number[] {
    const innerAndNotIntersect = (poly: DPolygon, p1: DPoint, p2: DPoint): boolean => {
      const l = p1.findLine(p2);
      const {center} = l;
      const intersections = poly.holes.reduce((a: boolean, hole: DPolygon) => a && Boolean(hole.clone().close()
        .intersection(l, true).length), Boolean(poly.clone().close()
        .intersection(l, true).length));
      const contain = poly.holes.reduce((a: boolean, hole: DPolygon) => a && !hole
        .contain(center), poly.contain(center));
      return !intersections && contain;
    };
 
    const getTriangle = (poly: DPolygon): [number, number, number] | void => {
      for (let i = 0; i < poly.length; i++) {
        const p0 = poly.at(0);
        const p1 = poly.at(1);
        const p2 = poly.at(2);
        if (innerAndNotIntersect(poly, p0, p2)) {
          poly.removePart(0, 1);
          return [
            p0.properties.index,
            p1.properties.index,
            p2.properties.index
          ];
        }
        poly.push(poly.shift());
      }
      return undefined;
    };
 
    let p = this.clone();
    let index = 0;
    p.points.forEach((f: DPoint) => {
      f.properties.index = index++;
    });
    p.holes.forEach((h: DPolygon) => {
      h.pPoints.forEach((f: DPoint) => {
        f.properties.index = index++;
      });
    });
    p = p.clockWise.open();
 
    while (p.holes.length) {
      const h = p.holes.shift()!
        .clone()
        .clockWise
        .reverse()
        .close();
      for (let i = 0; i < p.length; i++) {
        if (innerAndNotIntersect(p, p.first, h.first)) {
          p.insertAfter(0, ...h.points, p.first);
          break;
        }
        p.push(p.shift());
      }
    }
    const res: number[] = [];
    while (p.length > 3) {
      const triangle = getTriangle(p);
      if (triangle) {
        res.push(...triangle);
      }
    }
    res.push(...p.points.map((f: DPoint) => f.properties.index));
    return res;
  }
 
  get closed(): boolean {
    return this.first.equal(this.last);
  }
 
  /**
   * @param v
   * @param [quadrantSegments=64]
   * @param [type=DPolygon.CAP_ROUND] DPolygon.CAP_ROUND || DPolygon.CAP_FLAT || DPolygon.CAP_SQUARE
   */
  buffer(v: number, quadrantSegments: number = 64, type: number = DPolygon.CAP_ROUND): DPolygon {
    const reader = new jstsIo.WKTReader();
    const {noHoles, closed} = this;
    const points = reader
      .read(noHoles.toWKT(closed ? DPolygon.WKT_POLYGON : DPolygon.WKT_LINESTRING))
      .buffer(v, quadrantSegments, type)
      .getCoordinates() as { x: number; y: number }[];
    return new DPolygon(points.map(({x, y}: {x: number; y: number}) => new DPoint(x, y)));
  }
 
  /**
   * Return left and right buffers of polyline. With same direction as original line.
   *
   * For canvas: `[left, right]`
   *
   * For normal Cartesian coordinate system: `[right, left]`
   *
   * @param v
   * @param [quadrantSegments=64]
   */
  sideBuffers(v: number, quadrantSegments: number = 64): [DPolygon, DPolygon] {
    const {first, last} = this;
    const buffer = this.buffer(v, quadrantSegments, DPolygon.CAP_FLAT).open();
 
    const [start0, start1] = first.sortByDistance(buffer).points.map((r: DPoint) => r.properties.index);
    const [end0, end1] = last.sortByDistance(buffer).points.map((r: DPoint) => r.properties.index);
 
    const fromPoint = Math.min(Math.max(start0, start1), Math.max(end0, end1));
    const toPoint = Math.max(Math.min(start0, start1), Math.min(end0, end1));
    const linePart = new DPolygon(buffer.removePart(fromPoint - 1, toPoint - fromPoint + 1));
    buffer.unshift(buffer.pop());
    return [linePart.reverse(), buffer];
  }
 
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  setProperties(v: SetterFunction<Record<string, any>> | Record<string, any>): DPolygon {
    this.properties = typeof v === 'object' ? v : v(this);
    return this;
  }
 
  /**
   * Get [Bézier curve](https://en.wikipedia.org/wiki/B%C3%A9zier_curve)
   * @param [step=0.1]
   */
  bezier(step: number = 0.1): DPolygon {
    const res = new DPolygon();
    for (let i = 0; i < 1; i += step) {
      res.push(this.clone().getBezierPoint(i));
    }
    return res;
  }
 
  setGrowingHeight(from: number, to: number): DPolygon {
    const {fullLength} = this;
    let {first: prevPoint} = this;
    const d = to - from;
    let currentDistance = 0;
    this.loop()
      .setZ((p: DPoint) => {
        currentDistance += prevPoint.distance(p);
        prevPoint = p;
        return from + currentDistance / fullLength * d;
      })
      .run();
    return this;
  }
 
  /**
   * @ignore
   */
  loopPointsGenerator(): () => Generator<[DPoint, DPoint, undefined, number]>;
 
  /**
   * @ignore
   * @param withLine
   */
  loopPointsGenerator(withLine: True): () => Generator<[DPoint, DPoint, DLine, number]>;
 
  loopPointsGenerator(withLine: boolean = false): () => Generator<[DPoint, DPoint, DLine | undefined, number]> {
    // eslint-disable-next-line @typescript-eslint/no-this-alias,consistent-this
    const that = this;
    // eslint-disable-next-line func-names
    return function *() {
      for (let i = 0; i < that.length - 1; i++) {
        const p1 = that.at(i);
        const p2 = that.at(i + 1);
        yield [p1, p2, withLine ? p1.findLine(p2) : undefined, i];
      }
    };
  }
 
  private getBezierPoint(v: number): DPoint {
    if (this.length === 1) {
      return this.first;
    }
    for (const [p1, p2] of this.loopPointsGenerator()()) {
      p1.move(p2.clone().move(p1.clone().minus())
        .scale(v));
    }
    this.pop();
    return this.getBezierPoint(v);
  }
 
  private simpleIncludeX(p: DPoint) {
    const {x} = p;
    return this.minX <= x && this.maxX >= x;
  }
 
  private simpleIncludeY(p: DPoint) {
    const {y} = p;
    return this.minY <= y && this.maxY >= y;
  }
 
  private douglasPeucker(points: DPoint[], e: number): DPoint[] {
    let dMax = 0;
    let index = 0;
    const end = points.length - 1;
    const line = points[0].findLine(points[end]);
    for (let i = 1; i < end; i++) {
      const d = line.perpendicularDistance(points[i]);
      if (d > dMax) {
        index = i;
        dMax = d;
      }
    }
    if (dMax >= e) {
      const recResult1 = this.douglasPeucker(points.slice(0, index + 1), e);
      const recResult2 = this.douglasPeucker(points.slice(index), e);
      recResult1.pop();
      return [...recResult1, ...recResult2];
    }
    return [points[0], points[end]];
  }
 
  private goByPath(ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D, steps: number = this.length - 1) {
    const start = this.first;
    ctx.moveTo(start.x, start.y);
    for (let i = 1; i <= (steps % this.length); i++) {
      const {x, y} = this.at(i);
      ctx.lineTo(x, y);
    }
  }
 
  private getJSTSGeometry(p: DPolygon, unionThis: boolean, unionThat: boolean): Geometry | void {
    const unionOrIntersection = unionThat === unionThis;
    const reader = new jstsIo.WKTReader();
    const a = reader.read(this.noHoles.toWKT());
    const b = reader.read(p.noHoles.toWKT());
    if (!unionOrIntersection) {
      return a.difference(b);
    } else if (unionThis) {
      return a.union(b);
    } else if (!unionThis) {
      return a.intersection(b);
    }
    return undefined;
  }
 
  private simpleLogicFunction(p: DPolygon, unionThis: boolean, unionThat: boolean): DPolygon | null | DPolygon[] {
    const c = this.getJSTSGeometry(p, unionThis, unionThat);
    if (c) {
      const coordinates = c.getCoordinates() as { x: number; y: number }[];
      if (coordinates.length) {
        let result: DPolygon[] = coordinates.reduce(
          (ak: DPolygon[], {x, y}: { x: number; y: number }, index: number) => {
            const lastIndex = ak.length - 1;
            const t = new DPoint(x, y);
            const {first} = ak[lastIndex];
            if (t.equal(first)) {
              if (coordinates[index + 1]) {
                const nextPoint = new DPoint(coordinates[index + 1].x, coordinates[index + 1].y);
                if (ak[lastIndex].length > 1) {
                  ak.push(new DPolygon([nextPoint]));
                }
              }
            } else {
              ak[lastIndex].push(t);
            }
            return ak;
          },
          [new DPolygon([new DPoint(coordinates[0].x, coordinates[0].y)])]
        );
        if (unionThat && unionThis && result.length > 1) {
          for (const q of result) {
            for (const r of result) {
              if (q.has(r.first) && !q.equal(r)) {
                const index = q.findIndex(r.first);
                q.points.splice(index, 0, ...r.points);
                result = result.filter((h: DPolygon) => !h.equal(r));
                continue;
              }
              Iif (result.length < 2) {
                break;
              }
            }
            if (result.length < 2) {
              break;
            }
          }
        }
        result = result.filter((h: DPolygon) => h.length > 2).map((h: DPolygon) => h.close());
        for (const q of result) {
          for (const r of result) {
            if (result.length < 2) {
              break;
            }
            if (!q.equal(r)) {
              if (q.contain(r.first, true)) {
                q.holes.push(r);
                result = result.filter((h: DPolygon) => !h.equal(r));
              }
            }
          }
          if (result.length < 2) {
            break;
          }
        }
        if (result.length === 0) {
          return null;
        }
        if (result.length === 1) {
          return result[0].close();
        }
        return result.map((g: DPolygon) => g.close());
      }
    }
    return null;
  }
}