All files / src intersectionPolygon.js

0% Statements 0/349
0% Branches 0/214
0% Functions 0/38
0% Lines 0/304

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import {
  getPointInsideOutline,
  isInsidePolygon,
  isSamePoint2D
} from './geometry'
import {
  getIntersections,
  getNodeList,
  getEdgeList,
  getOutlineList
} from './splitMergePolygons'
 
// Determines whether a given polygon is self-intersecting
//is counterClockwise
export function isCounterClockwise(A, B, C) {
  return (C.y - A.y) * (B.x - A.x) > (B.y - A.y) * (C.x - A.x)
}
 
// Determines whether line segment AB intersects line segment CD
export function doLineSegmentsIntersect(A, B, C, D) {
  return (
    isCounterClockwise(A, C, D) != isCounterClockwise(B, C, D) &&
    isCounterClockwise(A, B, C) != isCounterClockwise(A, B, D)
  )
}
export function isSelfIntersecting(outline, isClosePolygon = true) {
  let isSelfIntersecting = false
  const length = outline.length
  //check if two nodes are in same position
  for (let k = 0; k < length; k++) {
    let A = outline[k]
    let B = outline[(k + 1) % length]
    if (isSamePoint2D(A, B)) return true
  }
  if (length < 4) return false
  let closeOffset = isClosePolygon ? 0 : 1
  //let AB and CD be two edges we are testing for intersection
  for (let k = 0; k < length - closeOffset; k++) {
    let A = outline[k]
    let B = outline[(k + 1) % length]
    let offset = k == 0 ? 0 : 1
    for (let j = k + 2; j < length - 1 + offset - closeOffset; j++) {
      let C = outline[j]
      let D = outline[(j + 1) % length]
      if (doLineSegmentsIntersect(A, B, C, D)) {
        isSelfIntersecting = true
        break
      }
    }
    if (isSelfIntersecting) {
      break
    }
  }
  return isSelfIntersecting
}
 
export function logicOperationOnPolygons(
  outline1,
  outline2,
  mode = 'intersect'
) {
  const fig1 = outline1.map((p) => {
    return { x: p.x, y: p.y, z: p.z }
  })
  fig1.push(fig1[0])
  const fig2 = outline2.map((p) => {
    return { x: p.x, y: p.y, z: p.z }
  })
  //nodeList:
  let dirtyNodeList = []
  fig1.forEach((p) => {
    dirtyNodeList.push(p)
  })
  fig2.forEach((p) => {
    dirtyNodeList.push(p)
  })
  //edgeList (just in term of indexes)
  const edges = fig2.map((p, index) => {
    return { outline: [p, fig2[(index + 1) % fig2.length]] }
  })
  let intersections = getIntersections({ outline: fig1 }, edges)
 
  //2. gather all nodes+intersection in a list[[x,y],[x,y]]
  const nodeList = getNodeList(intersections, edges, { outline: fig1 })
  //3. generate all edges not cut, those cut and those from construction polyline
 
  const edgeList = getEdgeList(
    nodeList,
    intersections,
    edges,
    { outline: fig1 },
    1
  )
  //4. run planar-face-discovery to get all cycles and rebuild our polygons
  try {
    const outlineList = getOutlineList(nodeList, edgeList)
    return filterPolygons(outlineList, fig1, fig2, mode)
  } catch (err) {
    console.error('error with getOutlineList', nodeList, edgeList, err)
    return []
  }
}
 
function filterPolygons(polygons, fig1, fig2, mode) {
  var filtered = []
  var c1, c2
  var point
  var bigPolygons = removeSmallPolygons(polygons, 0.0001)
  for (var i = 0; i < bigPolygons.length; i++) {
    point = getPointInsideOutline(
      bigPolygons[i],
      bigPolygons.filter((p, index) => index != i)
    )
    c1 = isInsidePolygon(point, fig1)
    c2 = isInsidePolygon(point, fig2)
    if (
      (mode === 'intersect' && c1 && c2) || //intersection
      (mode === 'cut1' && c1 && !c2) || //fig1 - fig2
      (mode === 'cut2' && !c1 && c2) || //fig2 - fig2
      (mode === 'sum' && (c1 || c2))
    ) {
      //fig1 + fig2
      //remove undefined point:
      bigPolygons[i] = bigPolygons[i].filter((p) => !!p)
      filtered.push(bigPolygons[i])
    }
  }
  return filtered
}
 
export function intersectOutlines(outline1, outline2) {
  const fig1 = outline1.map((p) => {
    return { x: p.x, y: p.y, z: p.z }
  })
  const fig2 = outline2.map((p) => {
    return { x: p.x, y: p.y, z: p.z }
  })
 
  return logicOperationOnPolygons(fig1, fig2, 'intersect')
}
 
function alignPolygon(polygon, points) {
  for (let i = 0; i < polygon.length; i++) {
    for (let j = 0; j < points.length; j++) {
      if (distance(polygon[i], points[j]) < 0.0001) polygon[i] = points[j]
    }
  }
  return polygon
}
 
function distance(p1, p2) {
  var dx = Math.abs(p1.x - p2.x)
  var dy = Math.abs(p1.y - p2.y)
  return Math.sqrt(dx * dx + dy * dy)
}
 
//check polygons for correctness
function checkPolygons(fig1, fig2) {
  var figs = [fig1, fig2]
  for (var i = 0; i < figs.length; i++) {
    if (figs[i].length < 3) {
      console.error('Polygon ' + (i + 1) + ' is invalid!')
      return false
    }
  }
  return true
}
 
//create array of edges of all polygons
function edgify(fig1, fig2) {
  //create primary array from all edges
  var primEdges = getEdges(fig1).concat(getEdges(fig2))
  var secEdges = []
  //check every edge
  for (var i = 0; i < primEdges.length; i++) {
    var points = []
    //for intersection with every edge except itself
    for (var j = 0; j < primEdges.length; j++) {
      if (i != j) {
        var interPoints = findEdgeIntersection(primEdges[i], primEdges[j])
        addNewPoints(interPoints, points)
      }
    }
    //add start and end points to intersection points
    let startPoint = primEdges[i][0]
    startPoint.t = 0
    let endPoint = primEdges[i][1]
    endPoint.t = 1
    addNewPoints([startPoint, endPoint], points)
    //sort all points by position on edge
    points = sortPoints(points)
    //break edge to parts
    for (var k = 0; k < points.length - 1; k++) {
      var edge = [
        { x: points[k].x, y: points[k].y },
        { x: points[k + 1].x, y: points[k + 1].y }
      ]
      // check for existanse in sec.array
      if (!edgeExists(edge, secEdges)) {
        //push if not exists
        secEdges.push(edge)
      }
    }
  }
  return secEdges
}
 
function addNewPoints(newPoints, points) {
  if (newPoints.length > 0) {
    //check for uniqueness
    for (var k = 0; k < newPoints.length; k++) {
      if (!pointExists(newPoints[k], points)) {
        points.push(newPoints[k])
      }
    }
  }
}
 
function sortPoints(points) {
  var p = points
  p.sort((a, b) => {
    if (a.t > b.t) return 1
    if (a.t < b.t) return -1
  })
  return p
}
 
function getEdges(fig) {
  var edges = []
  var len = fig.length
  for (var i = 0; i < len; i++) {
    edges.push([
      { x: fig[i % len].x, y: fig[i % len].y },
      { x: fig[(i + 1) % len].x, y: fig[(i + 1) % len].y }
    ])
  }
  return edges
}
 
function findEdgeIntersection(edge1, edge2) {
  var x1 = edge1[0].x
  var x2 = edge1[1].x
  var x3 = edge2[0].x
  var x4 = edge2[1].x
  var y1 = edge1[0].y
  var y2 = edge1[1].y
  var y3 = edge2[0].y
  var y4 = edge2[1].y
  var nom1 = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)
  var nom2 = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)
  var denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  var t1 = nom1 / denom
  var t2 = nom2 / denom
  var interPoints = []
  //1. lines are parallel or edges don't intersect
  if ((denom === 0 && nom1 !== 0) || t1 <= 0 || t1 >= 1 || t2 < 0 || t2 > 1) {
    return interPoints
  }
  //2. lines are collinear
  else if (nom1 === 0 && denom === 0) {
    //check if endpoints of edge2 lies on edge1
    for (var i = 0; i < 2; i++) {
      var classify = classifyPoint(edge2[i], edge1)
      //find position of this endpoints relatively to edge1
      if (classify.loc == 'ORIGIN' || classify.loc == 'DESTINATION') {
        interPoints.push({ x: edge2[i].x, y: edge2[i].y, t: classify.t })
      } else if (classify.loc == 'BETWEEN') {
        x = +(x1 + classify.t * (x2 - x1)).toFixed(9)
        y = +(y1 + classify.t * (y2 - y1)).toFixed(9)
        interPoints.push({ x: x, y: y, t: classify.t })
      }
    }
    return interPoints
  }
  //3. edges intersect
  else {
    for (var i = 0; i < 2; i++) {
      var classify = classifyPoint(edge2[i], edge1)
      if (classify.loc == 'ORIGIN' || classify.loc == 'DESTINATION') {
        interPoints.push({ x: edge2[i].x, y: edge2[i].y, t: classify.t })
      }
    }
    if (interPoints.length > 0) {
      return interPoints
    }
    var x = +(x1 + t1 * (x2 - x1)).toFixed(9)
    var y = +(y1 + t1 * (y2 - y1)).toFixed(9)
    interPoints.push({ x: x, y: y, t: t1 })
    return interPoints
  }
}
 
function classifyPoint(p, edge) {
  var ax = edge[1].x - edge[0].x
  var ay = edge[1].y - edge[0].y
  var bx = p.x - edge[0].x
  var by = p.y - edge[0].y
  var sa = ax * by - bx * ay
  if (p.x === edge[0].x && p.y === edge[0].y) {
    return { loc: 'ORIGIN', t: 0 }
  }
  if (p.x === edge[1].x && p.y === edge[1].y) {
    return { loc: 'DESTINATION', t: 1 }
  }
  var theta =
    (polarAngle([edge[1], edge[0]]) -
      polarAngle([
        { x: edge[1].x, y: edge[1].y },
        { x: p.x, y: p.y }
      ])) %
    360
  if (theta < 0) {
    theta = theta + 360
  }
  if (sa < -0.0000001) {
    return { loc: 'LEFT', theta: theta }
  }
  if (sa > 0.0000001) {
    return { loc: 'RIGHT', theta: theta }
  }
  if (ax * bx < 0 || ay * by < 0) {
    return { loc: 'BEHIND', theta: theta }
  }
  if (Math.sqrt(ax * ax + ay * ay) < Math.sqrt(bx * bx + by * by)) {
    return { loc: 'BEYOND', theta: theta }
  }
  var t
  if (ax !== 0) {
    t = bx / ax
  } else {
    t = by / ay
  }
  return { loc: 'BETWEEN', t: t }
}
 
function polarAngle(edge) {
  var dx = edge[1].x - edge[0].x
  var dy = edge[1].y - edge[0].y
  if (dx === 0 && dy === 0) {
    //console.error("Edge has zero length.");
    return false
  }
  if (dx === 0) {
    return dy > 0 ? 90 : 270
  }
  if (dy === 0) {
    return dx > 0 ? 0 : 180
  }
  var theta = (Math.atan(dy / dx) * 360) / (2 * Math.PI)
  if (dx > 0) {
    return dy >= 0 ? theta : theta + 360
  } else {
    return theta + 180
  }
}
 
function pointExists(p, points) {
  if (points.length === 0) {
    return false
  }
  for (var i = 0; i < points.length; i++) {
    if (p.x === points[i].x && p.y === points[i].y) {
      return true
    }
  }
  return false
}
 
function edgeExists(e, edges) {
  if (edges.length === 0) {
    return false
  }
  for (var i = 0; i < edges.length; i++) {
    if (equalEdges(e, edges[i])) return true
  }
  return false
}
 
function equalEdges(edge1, edge2) {
  if (
    (edge1[0].x === edge2[0].x &&
      edge1[0].y === edge2[0].y &&
      edge1[1].x === edge2[1].x &&
      edge1[1].y === edge2[1].y) ||
    (edge1[0].x === edge2[1].x &&
      edge1[0].y === edge2[1].y &&
      edge1[1].x === edge2[0].x &&
      edge1[1].y === edge2[0].y)
  ) {
    return true
  } else {
    return false
  }
}
 
function polygonate(edges) {
  var polygons = []
  var polygon = []
  var len = edges.length
  var midpoints = getMidpoints(edges)
  //start from every edge and create non-selfintersecting polygons
  for (var i = 0; i < len - 2; i++) {
    var org = { x: edges[i][0].x, y: edges[i][0].y }
    var dest = { x: edges[i][1].x, y: edges[i][1].y }
    var currentEdge = i
    var point
    var p
    var direction
    var stop
    //while we havn't come to the starting edge again
    for (direction = 0; direction < 2; direction++) {
      polygon = []
      stop = false
      while (polygon.length === 0 || !stop) {
        //add point to polygon
        polygon.push({ x: org.x, y: org.y })
        point = undefined
        //look for edge connected with end of current edge
        for (var j = 0; j < len; j++) {
          p = undefined
          //except itself
          if (!equalEdges(edges[j], edges[currentEdge])) {
            //if some edge is connected to current edge in one endpoint
            if (edges[j][0].x === dest.x && edges[j][0].y === dest.y) {
              p = edges[j][1]
            }
            if (edges[j][1].x === dest.x && edges[j][1].y === dest.y) {
              p = edges[j][0]
            }
            //compare it with last found connected edge for minimum angle between itself and current edge
            if (p) {
              var classify = classifyPoint(p, [org, dest])
              //if this edge has smaller theta then last found edge update data of next edge of polygon
              if (
                !point ||
                (classify.theta < point.theta && direction === 0) ||
                (classify.theta > point.theta && direction === 1)
              ) {
                point = { x: p.x, y: p.y, theta: classify.theta, edge: j }
              }
            }
          }
        }
        //change current edge to next edge
        org.x = dest.x
        org.y = dest.y
        dest.x = point.x
        dest.y = point.y
        currentEdge = point.edge
        //if we reach start edge
        if (equalEdges([org, dest], edges[i])) {
          stop = true
          //check polygon for correctness
          /*for (var k = 0; k < allPoints.length; k++) {
              //if some point is inside polygon it is incorrect
              if ((!pointExists(allPoints[k], polygon)) && (findPointInsidePolygon(allPoints[k], polygon))) {
                polygon = false;
              }
            }*/
          for (let k = 0; k < midpoints.length; k++) {
            //if some midpoint is inside polygon (edge inside polygon) it is incorrect
            if (findPointInsidePolygon(midpoints[k], polygon)) {
              polygon = false
            }
          }
        }
      }
      //add created polygon if it is correct and was not found before
      if (polygon && !polygonExists(polygon, polygons)) {
        polygons.push(polygon)
      }
    }
  }
  return polygons
}
 
function polygonExists(polygon, polygons) {
  //if array is empty element doesn't exist in it
  if (polygons.length === 0) return false
  //check every polygon in array
  for (var i = 0; i < polygons.length; i++) {
    //if lengths are not same go to next element
    if (polygon.length !== polygons[i].length) continue
    //if length are same need to check
    else {
      //if all the points are same
      for (var j = 0; j < polygon.length; j++) {
        //if point is not found break forloop and go to next element
        if (!pointExists(polygon[j], polygons[i])) break
        //if point found
        else {
          //and it is last point in polygon we found polygon in array!
          if (j === polygon.length - 1) return true
        }
      }
    }
  }
  return false
}
 
function filterPolygonsOld(polygons, fig1, fig2, mode) {
  var filtered = []
  var c1, c2
  var point
  var bigPolygons = removeSmallPolygons(polygons, 0.0001)
  for (var i = 0; i < bigPolygons.length; i++) {
    point = getPointInsidePolygon(bigPolygons[i])
    c1 = findPointInsidePolygon(point, fig1)
    c2 = findPointInsidePolygon(point, fig2)
    if (
      (mode === 'intersect' && c1 && c2) || //intersection
      (mode === 'cut1' && c1 && !c2) || //fig1 - fig2
      (mode === 'cut2' && !c1 && c2) || //fig2 - fig2
      (mode === 'sum' && (c1 || c2))
    ) {
      //fig1 + fig2
      filtered.push(bigPolygons[i])
    }
  }
  return filtered
}
 
function removeSmallPolygons(polygons, minSize) {
  var big = []
  for (var i = 0; i < polygons.length; i++) {
    if (polygonArea(polygons[i]) >= minSize) {
      big.push(polygons[i])
    }
  }
  return big
}
 
function polygonArea(p) {
  var len = p.length
  var s = 0
  for (var i = 0; i < len; i++) {
    s += Math.abs(
      p[i % len].x * p[(i + 1) % len].y - p[i % len].y * p[(i + 1) % len].x
    )
  }
  return s / 2
}
 
function getPointInsidePolygon(polygon) {
  var point
  var size = getSize(polygon)
  var edges = getEdges(polygon)
  var y = size.y.min + (size.y.max - size.y.min) / Math.PI
  var dy = (size.y.max - size.y.min) / 13
  var line = []
  var points
  var interPoints = []
  var pointsOK = false
  while (!pointsOK) {
    line = [
      { x: size.x.min - 1, y: y },
      { x: size.x.max + 1, y: y }
    ]
    //find intersections with all polygon edges
    for (var i = 0; i < edges.length; i++) {
      points = findEdgeIntersection(line, edges[i])
      //if edge doesn't lie inside line
      if (points && points.length === 1) {
        interPoints.push(points[0])
      }
    }
    interPoints = sortPoints(interPoints)
    //find two correct interpoints
    for (var i = 0; i < interPoints.length - 1; i++) {
      if (interPoints[i].t !== interPoints[i + 1].t) {
        //enable exit from loop and calculate point coordinates
        pointsOK = true
        point = { x: (interPoints[i].x + interPoints[i + 1].x) / 2, y: y }
      }
    }
    //all points are incorrect, need to change line parameters
    y = y + dy
    if ((y > size.y.max || y < size.y.min) && pointsOK === false) {
      pointsOK = true
      point = undefined
    }
  }
  return point
}
 
function getSize(polygon) {
  var size = {
    x: {
      min: polygon[0].x,
      max: polygon[0].x
    },
    y: {
      min: polygon[0].y,
      max: polygon[0].y
    }
  }
  for (var i = 1; i < polygon.length; i++) {
    if (polygon[i].x < size.x.min) size.x.min = polygon[i].x
    if (polygon[i].x > size.x.max) size.x.max = polygon[i].x
    if (polygon[i].y < size.y.min) size.y.min = polygon[i].y
    if (polygon[i].y > size.y.max) size.y.max = polygon[i].y
  }
  return size
}
 
function findPointInsidePolygon(point, polygon) {
  var cross = 0
  var edges = getEdges(polygon)
  var classify
  var org, dest
  for (var i = 0; i < edges.length; i++) {
    [org, dest] = edges[i]
    classify = classifyPoint(point, [org, dest])
    if (
      (classify.loc === 'RIGHT' && org.y < point.y && dest.y >= point.y) ||
      (classify.loc === 'LEFT' && org.y >= point.y && dest.y < point.y)
    ) {
      cross++
    }
    if (classify.loc === 'BETWEEN') return false
  }
  if (cross % 2) {
    return true
  } else {
    return false
  }
}
 
function getMidpoints(edges) {
  var midpoints = []
  var x, y
  for (var i = 0; i < edges.length; i++) {
    x = (edges[i][0].x + edges[i][1].x) / 2
    y = (edges[i][0].y + edges[i][1].y) / 2
    let classify = classifyPoint({ x: x, y: y }, edges[i])
    if (classify.loc != 'BETWEEN') {
      //console.error('Midpoint calculation error in intersect algo',edges)
    }
    midpoints.push({ x: x, y: y })
  }
  return midpoints
}