mirror of https://gitee.com/cf-fz/WebCAD.git
parent
3f459abcab
commit
8b262d2c68
@ -0,0 +1,59 @@
|
||||
import { Vec2 } from "./CheckIntersect";
|
||||
/*
|
||||
功能:判断线段是否存在交点
|
||||
ref:https://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/
|
||||
*/
|
||||
|
||||
// Given three colinear points p, q, r, the function checks if
|
||||
// point q lies on line segment 'pr'
|
||||
function onSegment(p: Vec2, q: Vec2, r: Vec2): boolean
|
||||
{
|
||||
if (q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) &&
|
||||
q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
// To find orientation of ordered triplet (p, q, r).
|
||||
// The function returns following values
|
||||
// 0 --> p, q and r are colinear
|
||||
// 1 --> Clockwise
|
||||
// 2 --> Counterclockwise
|
||||
function orientation(p: Vec2, q: Vec2, r: Vec2): number
|
||||
{
|
||||
// See https://www.geeksforgeeks.org/orientation-3-ordered-points/
|
||||
// for details of below formula.
|
||||
let val = (q.y - p.y) * (r.x - q.x) -
|
||||
(q.x - p.x) * (r.y - q.y);
|
||||
if (val == 0)
|
||||
return 0; // colinear
|
||||
return (val > 0) ? 1 : 2; // clock or counterclock wise
|
||||
}
|
||||
/**
|
||||
* 判断线段`p1q1`和线段`p2q2`是否相交.
|
||||
*/
|
||||
export function doIntersect(p1: Vec2, q1: Vec2, p2: Vec2, q2: Vec2): boolean
|
||||
{
|
||||
// Find the four orientations needed for general and
|
||||
// special cases
|
||||
let o1 = orientation(p1, q1, p2);
|
||||
let o2 = orientation(p1, q1, q2);
|
||||
let o3 = orientation(p2, q2, p1);
|
||||
let o4 = orientation(p2, q2, q1);
|
||||
// General case
|
||||
if (o1 !== o2 && o3 !== o4)
|
||||
return true;
|
||||
// Special Cases
|
||||
// p1, q1 and p2 are colinear and p2 lies on segment p1q1
|
||||
if (o1 === 0 && onSegment(p1, p2, q1))
|
||||
return true;
|
||||
// p1, q1 and q2 are colinear and q2 lies on segment p1q1
|
||||
if (o2 === 0 && onSegment(p1, q2, q1))
|
||||
return true;
|
||||
// p2, q2 and p1 are colinear and p1 lies on segment p2q2
|
||||
if (o3 === 0 && onSegment(p2, p1, q2))
|
||||
return true;
|
||||
// p2, q2 and q1 are colinear and q1 lies on segment p2q2
|
||||
if (o4 === 0 && onSegment(p2, q1, q2))
|
||||
return true;
|
||||
return false; // Doesn't fall in any of the above cases
|
||||
}
|
Loading…
Reference in new issue