All files / src geometry.js

11.62% Statements 75/645
6.3% Branches 21/333
8.33% Functions 8/96
11.78% Lines 70/594

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                                                                                                                                                                                                                              6x 6x         6x 6x     6x 6x   6x   6x 6x 6x                 18x       18x       60x         60x                 18x 18x                   18x 18x 18x   18x     18x       18x     18x 13x   18x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       3x 15x 15x 3x 15x 15x 15x 15x   3x                                                                                                                                                                                                                                   11x     11x 11x     11x 11x 11x 11x 11x 11x 11x   10x 4x 4x 4x 4x 4x     6x           6x 6x 6x 6x           6x           6x 6x     1x 1x 1x 1x     1x 7x         7x     1x     1x 7x         7x       11x                                                                                                                                                                                                                                                                                                                                                                                                        
import { mmTolerance, polygonCloseTolerance } from './config'
 
import {
  addVector,
  substractVector,
  multiplyVector,
  dotProduct,
  crossProduct,
  meanVector,
  vectorLength,
  normalizeVector,
} from './vector'
import { Quaternion } from './Quaternion'
import { inverse3x3matrix, multiplyMatrices } from './matrix'
import { Point } from './objects/Point'
import { Line } from './objects/Line'
import concaveman from './lib/concaveman'
 
export function getConcaveOutlines(selectedPanels, onePanelOutline) {
  let buckets = groupAdjacentObjects(selectedPanels)
  const outlines = []
  for (let bucketIndex = 0; bucketIndex < buckets.length; bucketIndex++) {
    outlines.push(
      getConcaveOutline(
        selectedPanels.filter((p, i) => buckets[bucketIndex].includes(i)),
        onePanelOutline
      )
    )
  }
  return { outlines, buckets }
}
 
export function getConcaveOutline(selectedPanels, onePanelOutline) {
  const points = selectedPanels.reduce((acc, cur) => {
    acc.push(...cur.outline.map((p) => [p.x, p.y]))
    return acc
  }, [])
  let AB = getDistanceBetweenPoints(onePanelOutline[0], onePanelOutline[1])
  let AD = getDistanceBetweenPoints(onePanelOutline[0], onePanelOutline[3])
  let longEdgeLength = Math.max(AB, AD) + 100
  var concaveResult = concaveman(points, 1, longEdgeLength)
  concaveResult.pop()
  let moduleFieldOutline = concaveResult.map((p) => {
    return {
      x: p[0],
      y: p[1],
      z: 0,
    }
  })
  //remove aligned nodes
  moduleFieldOutline = simplifyOutline(moduleFieldOutline)
  return moduleFieldOutline
}
export function simplifyOutline(initialOutline) {
  const simplifiedOutline = []
  initialOutline.forEach((p, k, outline) => {
    let len = outline.length
    let A = outline[(k - 1 + len) % len]
    let B = outline[(k + 1) % len]
    let M = outline[k % len]
    if (!isInsideEdge2D(M, A, B)) {
      simplifiedOutline.push(M)
    }
  })
  return simplifiedOutline
}
export function getSnapedValue(value, snaps, tolerance) {
  let closeSnapsItem = snaps.reduce(
    (acc, cur) => {
      let distance = Math.abs(cur - value)
      if (distance <= Math.min(tolerance, acc.distance)) {
        acc = { value: cur, distance }
      }
      return acc
    },
    { value, distance: tolerance }
  )
  return closeSnapsItem.value
}
export function getAngleInDegFromCanvasVector(v) {
  const angle = Math.atan2(v.y, v.x)
  return ((angle * 180) / Math.PI + 90 + 360) % 360
}
export function getOrthogonalLineABPassingInB(A, B) {
  if (isSamePoint3D(A, B)) {
    console.error("A == B Can't make a 90° line")
    return null
  }
  const C = new Point(A.x + A.y - B.y, A.y + B.x - A.x)
  return new Line(A, C, '')
}
// Return orthogonal line passing by C
export function getOrthogonalLinePassingByPoint(A, B, C) {
  if (isSamePoint3D(A, B)) {
    console.error("A == B Can't make a orthogonal line")
    return null
  }
  const M = new Point(C.x + B.y - A.y, C.y + A.x - B.x)
  return new Line(C, M, '')
}
 
export function getParallelLinePassingByPoint(A, B, C) {
  if (isSamePoint3D(A, B)) {
    console.error("A == B Can't make a parallel line")
    return null
  }
  const D = new Point(C.x + B.x - A.x, C.y + B.y - A.y, C.z + B.z - A.z)
  return new Line(C, D, '')
}
 
export function getDataAboutTwo3DLines(A, u, B, v) {
  let w = crossProduct(u, v)
  let m = [
    [u.x, v.x, w.x],
    [u.y, v.y, w.y],
    [u.z, v.z, w.z],
  ]
  let mInv = inverse3x3matrix(m)
  Iif (!mInv) {
    return null
  }
  let AB = substractVector(B, A)
  let [t1, t2, t3] = multiplyMatrices(mInv, [[AB.x], [AB.y], [AB.z]])
  //M point on Au
  let M = addVector(A, multiplyVector(t1, u))
  //N point on Bv
  let N = addVector(B, multiplyVector(-t2, v))
  let distance = get3DDistanceBetweenPoints(M, N)
  return { m, mInv, M, N, A, B, u, v, w, distance, t1, t2, t3 }
}
export function vectorFromAngleInDegCanvas(angle) {
  return {
    x: Math.sin((angle * Math.PI) / 180),
    y: -Math.cos((angle * Math.PI) / 180),
  }
}
export function getDistanceBetweenPoints(firstPoint, secondPoint) {
  const distance = Math.hypot(
    firstPoint.x - secondPoint.x,
    firstPoint.y - secondPoint.y
  )
  return distance
}
 
export function get3DDistanceBetweenPoints(firstPoint, secondPoint) {
  const distance = Math.hypot(
    firstPoint.x - secondPoint.x,
    firstPoint.y - secondPoint.y,
    firstPoint.z - secondPoint.z
  )
  return distance
}
 
export function getDegreeVectors(u, v) {
  return getDegree(u, { x: 0, y: 0, z: 0 }, v)
}
 
export function getDegree(H, I, J) {
  //return [-180,180] positive when clockwise, negative when anticlockwise
  let distanceFunction = get3DDistanceBetweenPoints
  Iif (
    H.z == undefined ||
    I.z == undefined ||
    J.z == undefined ||
    isNaN(H.z) ||
    isNaN(I.z) ||
    isNaN(J.z)
  ) {
    distanceFunction = getDistanceBetweenPoints
  }
  const a = distanceFunction(H, I)
  const b = distanceFunction(I, J)
  const c = distanceFunction(H, J)
 
  let angle = (Math.acos((a * a + b * b - c * c) / (2 * a * b)) * 180) / Math.PI
 
  //if 3 points are aligned
  Iif (isNaN(angle)) {
    angle = c < a || c < b ? 0 : 180
  }
 
  let sgn = -Math.sign(
    crossProduct(substractVector(H, I), substractVector(J, I)).z
  )
  if (sgn !== 0) {
    angle = sgn * angle
  }
  return angle
}
 
export function midPoint(firstPoint, secondPoint) {
  firstPoint.z = firstPoint.z || 0
  secondPoint.z = secondPoint.z || 0
  return {
    x: (firstPoint.x + secondPoint.x) / 2,
    y: (firstPoint.y + secondPoint.y) / 2,
    z: (firstPoint.z + secondPoint.z) / 2,
  }
}
 
export function isSamePoint3D(A, B) {
  return A.x == B.x && A.y == B.y && A.z == B.z
}
export function isAlmostSamePoint3D(A, B, tolerance) {
  return (
    Math.abs(A.x - B.x) < tolerance &&
    Math.abs(A.y - B.y) < tolerance &&
    Math.abs(A.z - B.z) < tolerance
  )
}
export function isSamePoint2D(A, B) {
  return A.x == B.x && A.y == B.y
}
export function isAlmostSamePoint2D(A, B, tolerance) {
  return Math.abs(A.x - B.x) < tolerance && Math.abs(A.y - B.y) < tolerance
}
export function isSameSegment2D(seg_0, seg_1) {
  let check_1 =
    isSamePoint2D(seg_0[0], seg_1[0]) && isSamePoint2D(seg_0[1], seg_1[1])
  let check_2 =
    isSamePoint2D(seg_0[0], seg_1[1]) && isSamePoint2D(seg_0[1], seg_1[0])
  return check_1 || check_2
}
export function isAlmostSameSegment2D(seg_0, seg_1, tolerance) {
  let check_1 =
    isAlmostSamePoint2D(seg_0[0], seg_1[0], tolerance) &&
    isAlmostSamePoint2D(seg_0[1], seg_1[1], tolerance)
  let check_2 =
    isAlmostSamePoint2D(seg_0[0], seg_1[1], tolerance) &&
    isAlmostSamePoint2D(seg_0[1], seg_1[0], tolerance)
  return check_1 || check_2
}
export function isSameSegment3D(seg_0, seg_1) {
  let check_1 =
    isSamePoint3D(seg_0[0], seg_1[0]) && isSamePoint3D(seg_0[1], seg_1[1])
  let check_2 =
    isSamePoint3D(seg_0[0], seg_1[1]) && isSamePoint3D(seg_0[1], seg_1[0])
  return check_1 || check_2
}
export function isAlmostSameSegment3D(seg_0, seg_1, tolerance) {
  let check_1 =
    isAlmostSamePoint3D(seg_0[0], seg_1[0], tolerance) &&
    isAlmostSamePoint3D(seg_0[1], seg_1[1], tolerance)
  let check_2 =
    isAlmostSamePoint3D(seg_0[0], seg_1[1], tolerance) &&
    isAlmostSamePoint3D(seg_0[1], seg_1[0], tolerance)
  return check_1 || check_2
}
export function isSameLine(AB, CD) {
  if (!AB || !CD) {
    console.error('AB or CD not defined')
    return false
  }
  if (AB.type != 'line' || CD.type != 'line') {
    return false
  }
  // if(AB.outline.length<2){return false}
  // if(CD.outline.length<2){return false}
  const A = AB.outline[0]
  const B = AB.outline[1]
  const C = CD.outline[0]
  const D = CD.outline[1]
  //is A on (CD)
  const P = getPointOnLine(A, C, D)
  if (getDistanceBetweenPoints(A, P) > 1) {
    return false
  }
  //is B on (CD)
  const M = getPointOnLine(B, C, D)
  if (getDistanceBetweenPoints(B, M) > 1) {
    return false
  }
 
  return true
}
export function distance2DToPolygon(point, vs) {
  let distance = Infinity
  if (isInsidePolygon(point, vs)) {
    return 0
  } else {
    for (let v of vs) {
      let distanceToNode = getDistanceBetweenPoints(point, v)
      distance = Math.min(distanceToNode, distance)
    }
    for (let k in vs) {
      let A = vs[k]
      let B = vs[(k + 1) % vs.length]
      //M projection of point on AB line
      if (!isSamePoint2D(A, B)) {
        let M = getPointOnLine(point, A, B)
        if (isInsideEdge2D(M, A, B)) {
          distance = Math.min(distance, getDistanceBetweenPoints(point, M))
        }
      }
    }
    return distance
  }
}
export function get2DBoundOfPolygon(vs) {
  const bound = {
    xMin: Infinity,
    xMax: -Infinity,
    yMin: Infinity,
    yMax: -Infinity,
  }
  for (let v of vs) {
    bound.xMin = Math.min(bound.xMin, v.x)
    bound.xMax = Math.max(bound.xMax, v.x)
    bound.yMin = Math.min(bound.yMin, v.y)
    bound.yMax = Math.max(bound.yMax, v.y)
  }
  return bound
}
export function getPointInsideOutline(vs, holes = []) {
  //draw an horizontal line between top and bottom
  const bound = get2DBoundOfPolygon(vs)
  const y = (bound.yMax + bound.yMin) / 2
  let xOfCrossingEdgeY = []
  for (let index = 0; index < vs.length; index++) {
    let nextIndex = (index + 1) % vs.length
    const A = vs[index]
    const B = vs[nextIndex]
    if ((A.y <= y && B.y > y) || (A.y >= y && B.y < y)) {
      let x = A.x + (B.x - A.x) * ((y - A.y) / (B.y - A.y))
      xOfCrossingEdgeY.push(x)
    }
  }
  if (xOfCrossingEdgeY.length < 2) {
    console.error('not enaugh edge crossing mid cut', vs)
    return
  }
  xOfCrossingEdgeY.sort((a, b) => a - b)
  let xLeft = xOfCrossingEdgeY[0]
  let xRight = xOfCrossingEdgeY[1]
  //dichotomy to get point outside of holes
  for (let hole of holes) {
    if (isPolygonInsidePolygon(vs, hole)) {
      return { x: (xLeft + xRight) / 2, y }
    }
  }
  let t = 0.1
  let count = 0
  let isInside = false
  let testPoint
  while (count < 10 && isInside == false) {
    count++
    let x = xLeft + t * (xRight - xLeft)
    testPoint = { x, y }
    isInside = true
    for (let hole of holes) {
      if (isInsidePolygon(testPoint, hole)) {
        isInside = false
        break
      }
    }
    if (isInside) {
      return testPoint
    } else {
      t = (Math.cos((count * Math.PI) / 11) + 1) / 2
    }
  }
  return testPoint
}
 
export function distanceToEdge2D(M, A, B) {
  const pA = { x: A.x, y: A.y, z: 0 }
  const pB = { x: B.x, y: B.y, z: 0 }
  const pM = { x: M.x, y: M.y, z: 0 }
  const AM = substractVector(pM, pA)
  const AB = substractVector(pB, pA)
  const det = AM.x * AB.y - AM.y * AB.x
  const ABLength = vectorLength(AB)
  const AMLength = vectorLength(AM)
  if (ABLength == 0 && isSamePoint2D(pM, pA)) {
    return true
  } else if (ABLength == 0 && !isSamePoint2D(pM, pA)) {
    return false
  } else if (AMLength == 0) {
    return true
  }
  const dotP = dotProduct(AM, AB) / (ABLength * AMLength)
  if (Math.abs(det) < 0.01 && dotP <= 1 && dotP >= 0) {
    return true
  } else {
    return false
  }
}
 
export function isInsideEdge2D(M, A, B) {
  const pA = { x: A.x, y: A.y, z: 0 }
  const pB = { x: B.x, y: B.y, z: 0 }
  const pM = { x: M.x, y: M.y, z: 0 }
  const angle = Math.abs(getDegree(pA, pM, pB))
  let result = false
  if (180 - angle <= 5) {
    result = true
  }
  return result
}
 
export function polygonsHaveSame2DOutline(outline1, outline2) {
  let sameLength = outline1.length == outline2.length
  return (
    sameLength &&
    outline1.every((p) => outline2.find((v) => v.x == p.x && v.y == p.y)) &&
    outline2.every((p) => outline1.find((v) => v.x == p.x && v.y == p.y))
  )
}
 
export function polygonsHaveSame3DOutline(outline1, outline2) {
  let sameLength = outline1.length == outline2.length
  return (
    sameLength &&
    outline1.every((p) => outline2.find((v) => v.x == p.x && v.y == p.y)) &&
    outline2.every((p) => outline1.find((v) => v.x == p.x && v.y == p.y))
  )
}
 
export function isOnBorderOfPolygon(point, vs) {
  let inside = false
  for (let i = 0, j = vs.length - 1; i < vs.length; j = i++) {
    if (isInsideEdge2D(point, vs[i], vs[j])) {
      inside = true
      break
    }
  }
  return inside
}
 
export function isStrictlyInsidePolygon(point, vs) {
  return isInsidePolygon(point, vs) && !isOnBorderOfPolygon(point, vs)
}
 
export function isInsidePolygon(point, vs) {
  // ray-casting algorithm based on
  // https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html/pnpoly.html
 
  const x = point.x
  const y = point.y
 
  let inside = false
 
  for (let i = 0, j = vs.length - 1; i < vs.length; j = i++) {
    const xi = vs[i].x
    const yi = vs[i].y
    const xj = vs[j].x
    const yj = vs[j].y
 
    const intersect =
      yi > y !== yj > y && x <= ((xj - xi) * (y - yi)) / (yj - yi) + xi
    if (intersect) inside = !inside
  }
  //if not really inside, let's check of edge
  if (!inside) {
    inside = isOnBorderOfPolygon(point, vs)
  }
  return inside
}
 
export function isPolygonInsidePolygon(innerOutline, outterOutline) {
  return innerOutline.every((p) => isInsidePolygon(p, outterOutline))
}
 
export function get3PathsFromPolyAndSplittingPath(
  outline,
  splittingPath,
  mmPerPx
) {
  //both outline and splittingPath are in Reality coordinate system
 
  //starting and ending points are defined by the splitting path
  let startingPoint = splittingPath[0]
  let endingPoint = splittingPath[splittingPath.length - 1]
  //We then identify which polygon vertex index is link to these points
  let startingIndex = outline.findIndex(
    (p) =>
      getDistanceBetweenPoints(startingPoint, p) <
      polygonCloseTolerance * mmPerPx
  )
  let endingIndex = outline.findIndex(
    (p) =>
      getDistanceBetweenPoints(endingPoint, p) < polygonCloseTolerance * mmPerPx
  )
  //let's set altitude of every created splitting point
  let nberSplittingPoint = splittingPath.length
  let startingAltitude = outline[startingIndex].z
  let endingAltitude = outline[endingIndex].z
  for (let k = 0; k < nberSplittingPoint; k++) {
    splittingPath[k].z =
      ((endingAltitude - startingAltitude) * k) / nberSplittingPoint +
      startingAltitude
  }
 
  let path1 = splittingPath
 
  if (startingIndex > endingIndex) {
    let tmp = startingIndex
    startingIndex = endingIndex
    endingIndex = tmp
 
    tmp = endingPoint
    endingPoint = startingPoint
    startingPoint = tmp
    path1.reverse()
  }
 
  let path2 = outline
  //rotate polygon to have startingIndex point at index 0
  //rotate "startingIndex" times to the left
  for (let k = 0; k < startingIndex; k++) {
    path2.push(path2.shift())
  }
  let path3 = path2.splice(0, 1 + endingIndex - startingIndex) // start and finish with the commun points
  path2 = [endingPoint, ...path2, startingPoint]
  path2.reverse()
  return [path1, path2, path3]
}
 
export function get2PolygonsOutlineFrom3Paths(path1, path2, path3) {
  //check if path starts and ends at the same point
  if (
    !(
      path1[0].x == path2[0].x &&
      path2[0].x == path3[0].x &&
      path1[0].y == path2[0].y &&
      path2[0].y == path3[0].y &&
      path1[path1.length - 1].x == path2[path2.length - 1].x &&
      path2[path2.length - 1].x == path3[path3.length - 1].x &&
      path1[path1.length - 1].y == path2[path2.length - 1].y &&
      path2[path2.length - 1].y == path3[path3.length - 1].y
    )
  ) {
    console.error('path problem')
  }
  let refPoint1 = midPoint(path1[0], path1[1])
  let refPoint2 = midPoint(path2[0], path2[1])
  let poly1 = { outline: [] }
  let poly2 = { outline: [] }
 
  if (isInsidePolygon(refPoint1, [...path2, ...path3])) {
    //path1 is inside path2 & path 3
    path1.reverse()
    path1.pop()
    path1.shift()
    poly1.outline = [...path1, ...path2]
    poly2.outline = [...path1, ...path3]
  } else if (isInsidePolygon(refPoint2, [...path1, ...path3])) {
    //path2 is inside path1 & path 3
    path2.reverse()
    path2.pop()
    path2.shift()
    poly1.outline = [...path2, ...path1]
    poly2.outline = [...path2, ...path3]
  } else {
    //path3 is inside path1 & path 2
    path3.reverse()
    path3.pop()
    path3.shift()
    poly1.outline = [...path3, ...path1]
    poly2.outline = [...path3, ...path2]
  }
 
  return [poly1, poly2]
}
 
export function getPointOnLine(M, A, B) {
  function zValueNotDefined(P) {
    return P.z == undefined || isNaN(P.z)
  }
  //Calcul of P, Projection of M on line AB
  if (isSamePoint3D(A, B)) {
    console.error("A and B don't make a line : A==B")
    return null
  }
  let P = {}
  if (zValueNotDefined(M) || zValueNotDefined(A) || zValueNotDefined(B)) {
    const AM = {
      x: M.x - A.x,
      y: M.y - A.y,
    }
    const AB = {
      x: B.x - A.x,
      y: B.y - A.y,
    }
 
    const dot = AM.x * AB.x + AM.y * AB.y
    const distanceAB = getDistanceBetweenPoints(A, B)
    let param = -1
    if (distanceAB == 0) {
      //A et B sont confondu
      console.error("A and B don't make a line : A==B")
      P = M
    } else {
      // in case of 0 length line
      const distanceAP = dot / distanceAB
      P.x = A.x + (distanceAP * AB.x) / distanceAB
      P.y = A.y + (distanceAP * AB.y) / distanceAB
    }
  } else {
    //make 3D projection on line
    const AM = {
      x: M.x - A.x,
      y: M.y - A.y,
      z: M.z - A.z,
    }
    const AB = {
      x: B.x - A.x,
      y: B.y - A.y,
      z: B.z - A.z,
    }
 
    const dot = AM.x * AB.x + AM.y * AB.y + AM.z * AB.z
    const distanceAB = get3DDistanceBetweenPoints(A, B)
    let param = -1
    if (distanceAB == 0) {
      //A et B sont confondu
      console.error("A and B don't make a line : A==B")
      P = M
    } else {
      // in case of 0 length line
      const distanceAP = dot / distanceAB
      P.x = A.x + (distanceAP * AB.x) / distanceAB
      P.y = A.y + (distanceAP * AB.y) / distanceAB
      P.z = A.z + (distanceAP * AB.z) / distanceAB
    }
  }
  //projection of the point to the line
  return P
}
export function translate2D(point, vector) {
  return {
    ...point,
    x: point.x + vector.x,
    y: point.y + vector.y,
    z: point.z,
  }
}
 
export function normalizedVectorTowardInsideAngle(H, I, J) {
  const IH = normalizeVector(substractVector(H, I))
  const IJ = normalizeVector(substractVector(J, I))
  const sumVector = addVector(IH, IJ)
  let res = {}
  if (vectorLength(sumVector) < 0.1) {
    res.x = IJ.y
    res.y = -IJ.x
    res.z = 0
  } else {
    res = normalizeVector(sumVector)
  }
  return res
}
 
export function isPointBetweenSegment(A, B, C) {
  const AB = getDistanceBetweenPoints(A, B)
  const AC = getDistanceBetweenPoints(A, C)
  const BC = getDistanceBetweenPoints(C, B)
  const isBetween = AB < BC && AC < BC
  return isBetween
}
export function get3pointNotAlignedFromOutline(outline) {
  if (outline.length < 3) {
    return null
  }
  const A = outline[0]
  const B = outline[1]
  let C = outline[2]
  let k = 2
  while (k < outline.length && getDegree(A, B, C) % 180 == 0) {
    C = outline[k]
    k++
  }
  if (k == outline.length) {
    return null
  }
  return [A, B, C]
}
export function getNormalVectortoEdgeTowardPolygon(k, outline) {
  const A = outline[k]
  const B = outline[(k + 1) % outline.length]
  const AB = substractVector(B, A)
  const ABC = get3pointNotAlignedFromOutline(outline)
  if (!ABC) {
    return null
  }
  let polyNormalVector = getNormalVectorFrom3Points(...ABC)
  const isOutlineClockwise = isClockWise(outline)
  if (polyNormalVector.z < 0) {
    polyNormalVector = multiplyVector(-1, polyNormalVector)
  }
  if (!isOutlineClockwise) {
    polyNormalVector = multiplyVector(-1, polyNormalVector)
  }
  let ABnormal = crossProduct(AB, polyNormalVector)
  let u = normalizeVector(ABnormal)
  return u
}
export function getNormalVectorFrom3Points(A, B, C) {
  const AB = substractVector(B, A)
  const BC = substractVector(C, B)
  const normalVector = normalizeVector(crossProduct(AB, BC))
  return normalVector
}
export function normalVectorWithDirectionAndIncline(direction, incline) {
  return {
    x:
      Math.sin((direction * Math.PI) / 180) *
      Math.sin((incline * Math.PI) / 180),
    y:
      Math.cos((direction * Math.PI) / 180) *
      Math.sin((incline * Math.PI) / 180),
    z: Math.cos((incline * Math.PI) / 180),
  }
}
export function inclineWithNormalVector(normalVector) {
  const angleRad = Math.acos(dotProduct(normalVector, { x: 0, y: 0, z: 1 }))
  const angleDeg = (angleRad * 180) / Math.PI
  return angleDeg
}
 
export function directionWithNormalVector(normalVector) {
  if (normalVector.z < 0) {
    normalVector = multiplyVector(-1, normalVector)
  }
  const normalVectorProjectionToGround = normalizeVector({
    ...normalVector,
    z: 0,
  })
  if (isSamePoint3D(normalVectorProjectionToGround, { x: 0, y: 0, z: 0 }))
    return 0
 
  const angleRad = Math.acos(
    dotProduct(normalVectorProjectionToGround, { x: 0, y: 1, z: 0 })
  )
  let angleDeg = (angleRad * 180) / Math.PI
  if (normalVectorProjectionToGround.x < 0) {
    angleDeg = 360 - angleDeg
  }
  return angleDeg
}
 
export function verticalProjectionOnPlane(p, n, o) {
  const d = dotProduct(n, o)
  const projectedHeight = (d - n.x * p.x - n.y * p.y) / n.z
  const projectedPoint = { ...p, z: projectedHeight }
  return projectedPoint
}
 
export function calcPolygonArea(vertices) {
  var total = 0
 
  for (var i = 0, l = vertices.length; i < l; i++) {
    var addX = vertices[i].x
    var addY = vertices[i == vertices.length - 1 ? 0 : i + 1].y
    var subX = vertices[i == vertices.length - 1 ? 0 : i + 1].x
    var subY = vertices[i].y
 
    total += addX * addY * 0.5
    total -= subX * subY * 0.5
  }
 
  return Math.abs(total)
}
 
export function pointProjectionOnPlane(p, n, o) {
  //formula for p', projection of p on plane defined by normalvector n passing by o
  //p' = p - (n ⋅ (p - o)) × n
  const pPrim = substractVector(
    p,
    multiplyVector(dotProduct(n, substractVector(p, o)), n)
  )
  return pPrim
}
 
export function isClockWise(outline) {
  let sum = 0
  let minX = Math.min(...outline.map((p) => p.x))
  let minY = Math.min(...outline.map((p) => p.y))
  for (let i = 0; i < outline.length; i++) {
    let current = outline[i]
    let next = outline[(i + 1) % outline.length]
    let item = 0.5 * (next.x - current.x) * (next.y + current.y - 2 * minY)
    sum += item
  }
  return sum > 0
}
export function groupAdjacentObjects(objects) {
  if (!objects || objects.length == 0) return []
  // objects with 2D indexes
  // Check if the objects form an adjacent group
  let numberOfObjects = objects.length
  let indexList = Array.from({ length: numberOfObjects }, (e, i) => i)
  let buckets = []
  let inBucket = 0
  while (inBucket < objects.length) {
    let detatchedIndex = indexList.find((i) => !buckets.flat().includes(i))
    if (detatchedIndex == null) break
    let queue = [detatchedIndex]
    let visited = []
    while (queue.length > 0) {
      const currentObjectIndex = queue.pop()
      if (visited.indexOf(currentObjectIndex) == -1) {
        //if next queued index hasn't been visited, we mark it as visited and we collect all neighbourg to queue
        visited.push(currentObjectIndex)
        let x = objects[currentObjectIndex].index[0]
        let y = objects[currentObjectIndex].index[1]
        const left = objects.findIndex(
          (o) => o.index[0] == x - 1 && o.index[1] == y
        )
        const right = objects.findIndex(
          (o) => o.index[0] == x + 1 && o.index[1] == y
        )
        const top = objects.findIndex(
          (o) => o.index[0] == x && o.index[1] == y - 1
        )
        const bottom = objects.findIndex(
          (o) => o.index[0] == x && o.index[1] == y + 1
        )
        if (left != -1 && visited.indexOf(left) == -1) queue.push(left)
        if (right != -1 && visited.indexOf(right) == -1) queue.push(right)
        if (top != -1 && visited.indexOf(top) == -1) queue.push(top)
        if (bottom != -1 && visited.indexOf(bottom) == -1) queue.push(bottom)
      }
    }
    inBucket += visited.length
    buckets.push(visited)
  }
 
  return buckets
}
// Function to check if two indexes are adjacent
export function areAdjacent(objects) {
  if (!objects || objects.length == 0) return false
  // objects with 2D indexes
  // Check if the objects form an adjacent group
  let visited = []
  let queue = [0]
 
  while (queue.length > 0) {
    const currentObjectIndex = queue.pop()
    if (visited.indexOf(currentObjectIndex) == -1) {
      //if next queued index hasn't been visited, we mark it as visited and we collect all neighbourg to queue
      visited.push(currentObjectIndex)
      let x = objects[currentObjectIndex].index[0]
      let y = objects[currentObjectIndex].index[1]
      const left = objects.findIndex(
        (o) => o.index[0] == x - 1 && o.index[1] == y
      )
      const right = objects.findIndex(
        (o) => o.index[0] == x + 1 && o.index[1] == y
      )
      const top = objects.findIndex(
        (o) => o.index[0] == x && o.index[1] == y - 1
      )
      const bottom = objects.findIndex(
        (o) => o.index[0] == x && o.index[1] == y + 1
      )
      if (left != -1 && visited.indexOf(left) == -1) queue.push(left)
      if (right != -1 && visited.indexOf(right) == -1) queue.push(right)
      if (top != -1 && visited.indexOf(top) == -1) queue.push(top)
      if (bottom != -1 && visited.indexOf(bottom) == -1) queue.push(bottom)
    }
  }
  return visited.length == objects.length
}
export function getOutlineBoundingBox(outline) {
  let minX = Infinity,
    minY = Infinity,
    minZ = Infinity,
    maxX = -Infinity,
    maxY = -Infinity,
    maxZ = -Infinity
 
  outline.forEach(({ x, y, z }) => {
    if (x < minX) minX = x
    if (x > maxX) maxX = x
    if (y < minY) minY = y
    if (y > maxY) maxY = y
    if (z < minZ) minZ = z
    if (z > maxZ) maxZ = z
  })
  return {
    x: { min: minX, max: maxX },
    y: { min: minY, max: maxY },
    z: { min: minZ, max: maxZ },
  }
}
 
export function getMarginPoints(
  A,
  B,
  C,
  marginA,
  marginB,
  clockwiseNormalVector
) {
  //clockwiseNormalVector gives the direction of the margin using the right hand rule with
  //1st vector AB, second clockwiseNormalVector, major gives the direction of the margin
  const vec_n = normalizeVector(
    crossProduct(substractVector(B, A), clockwiseNormalVector)
  )
  const n = multiplyVector(marginA, vec_n)
  const vec_m = normalizeVector(
    crossProduct(substractVector(C, B), clockwiseNormalVector)
  )
  const m = multiplyVector(marginB, vec_m)
  const BA = substractVector(A, B)
  const BC = substractVector(C, B)
  const isConvexe = dotProduct(crossProduct(BA, BC), clockwiseNormalVector) >= 0
  let pointsArray = [[], []]
  const angle = getDegree(A, B, C)
  if (isConvexe) {
    //check for parallelism
    if (Math.abs(angle) > 170) {
      const midMarginDirection = multiplyVector(0.5, addVector(vec_n, vec_m))
      const Ka = addVector(B, multiplyVector(marginA, midMarginDirection))
      const Kb = addVector(B, multiplyVector(marginB, midMarginDirection))
      pointsArray[0] = [Ka]
      pointsArray[1] = [Kb]
    } else {
      //get intersection point
      let { N, M } = getDataAboutTwo3DLines(
        addVector(B, n),
        BA,
        addVector(B, m),
        BC
      )
      const distanceAB = getDistanceBetweenPoints(B, A)
      const distanceMB = getDistanceBetweenPoints(B, M)
      const distanceNB = getDistanceBetweenPoints(B, M)
      Iif (distanceMB > distanceAB && distanceMB > 0) {
        M = addVector(
          B,
          multiplyVector(distanceAB / distanceMB, substractVector(M, B))
        )
      }
      Iif (distanceNB > distanceAB && distanceNB > 0) {
        N = addVector(
          B,
          multiplyVector(distanceAB / distanceNB, substractVector(N, B))
        )
      }
      pointsArray[0] = [M]
      pointsArray[1] = [N]
    }
  } else {
    const roundedAngle = 180 - Math.abs(angle)
    const midVector = Quaternion.slerpFromVectors(vec_n, vec_m, 0.5)
    const numPointPerMargin = 2 + Math.round(roundedAngle / 20)
    Iif (marginA == 0) {
      pointsArray[0] = [B]
    } else {
      for (let k = 0; k <= numPointPerMargin; k++) {
        let w = Quaternion.slerpFromVectors(
          n,
          multiplyVector(marginA, midVector),
          k / numPointPerMargin
        )
        pointsArray[0].push(addVector(B, w))
      }
    }
    Iif (marginB == 0) {
      pointsArray[1] = [B]
    } else {
      for (let k = 0; k <= numPointPerMargin; k++) {
        let w = Quaternion.slerpFromVectors(
          multiplyVector(marginB, midVector),
          m,
          k / numPointPerMargin
        )
        pointsArray[1].push(addVector(B, w))
      }
    }
  }
  return pointsArray
}
 
export function calculateArea(vertices) {
  var n = vertices.length
  var area = 0
  for (var i = 0; i < n; i++) {
    var v_current = substractVector(vertices[i], vertices[0])
    var v_next = substractVector(vertices[(i + 1) % n], vertices[0])
    const product = crossProduct(v_current, v_next)
    const sgn = product.z > 0 ? -1 : 1
    area += 0.5 * sgn * vectorLength(product)
  }
  return Math.abs(area)
}
 
export function hasNaN(arr) {
  for (let i = 0; i < arr.length; i++) {
    // check if array value is false or NaN
    if (Number.isNaN(arr[i])) {
      return true
    }
  }
  return false
}
 
export function calculatePositionSubHandle(polygon, i, mmPerPx) {
  const outline = polygon.outline
  const length = outline.length
 
  const h = (i - 1 + length) % length
  const j = (i + 1) % length
 
  //calculation of the angle where we need to insert the handle.
  const IH_angle = Math.atan2(
    outline[h].y - outline[i].y,
    outline[h].x - outline[i].x
  )
  const JI_angle = Math.atan2(
    outline[j].y - outline[i].y,
    outline[j].x - outline[i].x
  )
  const handle_angle = (IH_angle + JI_angle) / 2
 
  //d is the handle distance in px inside polygon vertex
  const d = 20 * mmPerPx
  const r = d / 4
  let handleX = outline[i].x + d * Math.cos(handle_angle)
  let handleY = outline[i].y + d * Math.sin(handle_angle)
  let handleZ = outline[i].z
 
  //check if handle is inside the polygon, if not, change where the handle is displayed
  const isInside = isInsidePolygon(
    { x: handleX, y: handleY, z: handleZ },
    outline
  )
  if (!isInside) {
    handleX = outline[i].x - d * Math.cos(handle_angle)
    handleY = outline[i].y - d * Math.sin(handle_angle)
  }
  return { x: handleX, y: handleY, z: outline[i].z }
}
export function triangleArea(A, B, C) {
  var AB = substractVector(B, A)
  var AC = substractVector(C, A)
  const product = crossProduct(AB, AC)
  let area = vectorLength(product) / 2
  return area
}
export function getIndexesOfBiggestTriangle(points) {
  return getIndexesOfBiggestTriangleWithFixedIndexes(points, [])
}
export function arrayIntersection(array1, array2) {
  return array1.filter((value) => array2.includes(value))
}
export function getIndexesOfBiggestTriangleWithFixedIndexes(
  points,
  fixedIndexes,
  preferedIndexes = [],
  areaMinFactor = 4
) {
  if (points.length < 3) {
    throw new Error('not enough points to make a triangle')
  }
  fixedIndexes = [...new Set(fixedIndexes)]
  if (fixedIndexes.length >= 3) {
    return getIndexesOfBiggestTriangleWithFixedIndexes(points, [], fixedIndexes)
  }
  let minArea = calculateArea(points) / areaMinFactor
  let preferedAndFixedIndexes = [...fixedIndexes, ...preferedIndexes]
  preferedAndFixedIndexes = [...new Set(preferedAndFixedIndexes)]
  let maxArea = minArea
  let maxNumberOfPreferedOrFixedIndexes = -1
  let maxTriangle = [0, 1, 2]
  let triangleFound = false
  for (let i = 0; i < points.length - 2; i++) {
    for (let j = i + 1; j < points.length - 1; j++) {
      for (let k = j + 1; k < points.length; k++) {
        if (
          arrayIntersection(fixedIndexes, [i, j, k]).length ==
          fixedIndexes.length
        ) {
          const numberOfPreferedOrFixedIndexes = arrayIntersection(
            preferedAndFixedIndexes,
            [i, j, k]
          ).length
          if (
            numberOfPreferedOrFixedIndexes >= maxNumberOfPreferedOrFixedIndexes
          ) {
            let area = triangleArea(points[i], points[j], points[k])
            if (
              area >= minArea &&
              numberOfPreferedOrFixedIndexes > maxNumberOfPreferedOrFixedIndexes
            ) {
              maxArea = minArea
            }
            if (area >= maxArea) {
              triangleFound = true
              maxArea = area
              maxNumberOfPreferedOrFixedIndexes = numberOfPreferedOrFixedIndexes
              maxTriangle = [i, j, k]
            }
          }
        }
      }
    }
  }
  if (!triangleFound && areaMinFactor <= 8) {
    areaMinFactor += 2
    return getIndexesOfBiggestTriangleWithFixedIndexes(
      points,
      fixedIndexes,
      preferedIndexes,
      areaMinFactor
    )
  }
  return maxTriangle
}
export function getIndexesOfBiggestTriangleWithTwoFixedIndexes(
  points,
  fixedIndexes,
  preferedIndexes = [],
  areaMinFactor = 4
) {
  fixedIndexes = [...new Set(fixedIndexes)]
  let preferedAndFixedIndexes = [...fixedIndexes, ...preferedIndexes]
  preferedAndFixedIndexes = [...new Set(preferedAndFixedIndexes)]
  if (points.length < 3 || fixedIndexes.length < 3) {
    throw new Error('not enough points to make a triangle')
  }
  let minArea = calculateArea(points) / areaMinFactor
  let maxArea = minArea
  let maxNumberOfPreferedOrFixedIndexes = -1
  let maxTriangle = [0, 1, 2]
  let triangleFound = false
  for (let i = 0; i < points.length - 2; i++) {
    for (let j = i + 1; j < points.length - 1; j++) {
      for (let k = j + 1; k < points.length; k++) {
        if (arrayIntersection(fixedIndexes, [i, j, k]).length == 2) {
          const numberOfPreferedOrFixedIndexes = arrayIntersection(
            preferedAndFixedIndexes,
            [i, j, k]
          ).length
          if (
            numberOfPreferedOrFixedIndexes >= maxNumberOfPreferedOrFixedIndexes
          ) {
            let area = triangleArea(points[i], points[j], points[k])
            if (
              area >= minArea &&
              numberOfPreferedOrFixedIndexes > maxNumberOfPreferedOrFixedIndexes
            ) {
              maxArea = minArea
            }
            //give advantages to connected area
            if (area > maxArea) {
              triangleFound = true
              maxArea = area
              maxNumberOfPreferedOrFixedIndexes = numberOfPreferedOrFixedIndexes
              maxTriangle = [i, j, k]
            }
          }
        }
      }
    }
  }
  if (!triangleFound && areaMinFactor <= 8) {
    areaMinFactor += 2
    return getIndexesOfBiggestTriangleWithTwoFixedIndexes(
      points,
      fixedIndexes,
      preferedIndexes,
      areaMinFactor
    )
  }
  return maxTriangle
}