Intersection.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import Coordinate from '../geom/Coordinate'
  2. import Double from '../../../../java/lang/Double'
  3. export default class Intersection {
  4. static intersection(p1, p2, q1, q2) {
  5. const minX0 = p1.x < p2.x ? p1.x : p2.x
  6. const minY0 = p1.y < p2.y ? p1.y : p2.y
  7. const maxX0 = p1.x > p2.x ? p1.x : p2.x
  8. const maxY0 = p1.y > p2.y ? p1.y : p2.y
  9. const minX1 = q1.x < q2.x ? q1.x : q2.x
  10. const minY1 = q1.y < q2.y ? q1.y : q2.y
  11. const maxX1 = q1.x > q2.x ? q1.x : q2.x
  12. const maxY1 = q1.y > q2.y ? q1.y : q2.y
  13. const intMinX = minX0 > minX1 ? minX0 : minX1
  14. const intMaxX = maxX0 < maxX1 ? maxX0 : maxX1
  15. const intMinY = minY0 > minY1 ? minY0 : minY1
  16. const intMaxY = maxY0 < maxY1 ? maxY0 : maxY1
  17. const midx = (intMinX + intMaxX) / 2.0
  18. const midy = (intMinY + intMaxY) / 2.0
  19. const p1x = p1.x - midx
  20. const p1y = p1.y - midy
  21. const p2x = p2.x - midx
  22. const p2y = p2.y - midy
  23. const q1x = q1.x - midx
  24. const q1y = q1.y - midy
  25. const q2x = q2.x - midx
  26. const q2y = q2.y - midy
  27. const px = p1y - p2y
  28. const py = p2x - p1x
  29. const pw = p1x * p2y - p2x * p1y
  30. const qx = q1y - q2y
  31. const qy = q2x - q1x
  32. const qw = q1x * q2y - q2x * q1y
  33. const x = py * qw - qy * pw
  34. const y = qx * pw - px * qw
  35. const w = px * qy - qx * py
  36. const xInt = x / w
  37. const yInt = y / w
  38. if (Double.isNaN(xInt) || (Double.isInfinite(xInt) || Double.isNaN(yInt)) || Double.isInfinite(yInt))
  39. return null
  40. return new Coordinate(xInt + midx, yInt + midy)
  41. }
  42. }