keverman

Line intersection

Jan 12th, 2019 (edited)
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. struct point
  2. {
  3.     int x, y;
  4.  
  5.     point(int x, int y) : x(x), y(y) {}
  6.  
  7.     point operator-(point& other)
  8.     {
  9.         return point(x - other.x, y - other.y);
  10.     }
  11. };
  12.  
  13. long long cp(point a, point b)
  14. {
  15.     return (long long)a.x * b.y - (long long)a.y * b.x;
  16. }
  17.  
  18. bool intersect(point a, point b, point c, point d)
  19. {
  20.     // Create change vectors and their cross product
  21.     point r = b - a, s = d - c;
  22.     long long cp_rs = cp(r, s);
  23.  
  24.     if (cp_rs == 0) // Lines are parallel
  25.     {
  26.         if (cp(c - a, r) == 0) // Lines are colinear
  27.         {
  28.             if (r.x == 0 && s.x == 0) // Check if they're overlaping
  29.             {
  30.                 if (a.y > b.y) swap(a, b);
  31.                 if (c.y > d.y) swap(c, d);
  32.                 return (b.y - c.y >= 0 && d.y - a.y >= 0);
  33.             }
  34.  
  35.             else
  36.             {
  37.                 if (a.x > b.x) swap(a, b);
  38.                 if (c.x > d.x) swap(c, d);
  39.                 return (b.x - c.x >= 0 && d.x - a.x >= 0);
  40.             }
  41.         }
  42.  
  43.         return false;
  44.     }
  45.  
  46.     else // Lines aren't parallel
  47.     {
  48.         // Check where they intersect
  49.         double t = (double)cp(c - a, s) / cp_rs;
  50.         double u = (double)cp(c - a, r) / cp_rs;
  51.  
  52.         if (t <= 1 && t >= 0 && u <= 1 && u >= 0) return true; // Intersect without prolongation
  53.         return false; // Intersect with prolongation
  54.     }
  55. }
Add Comment
Please, Sign In to add comment