64,682
社区成员
发帖
与我相关
我的任务
分享
typedef struct
{
double x;
double y;
} Point;
#define EPS .1e-6
int dblcmp(double d)
{
if (fabs(d)<EPS)
return 0;
return (d>0)?1:-1;
}
double det(double x1, double y1, double x2, double y2)
{
return x1*y2 - x2*y1;
}
double cross(Point a, Point b, Point c)
{
return det(b.x-a.x, b.y-a.y, c.x-a.x, c.y-a.y);
}
double dotdet(double x1, double y1, double x2, double y2)
{
return x1*x2 + y1*y2;
}
double dot(Point a, Point b, Point c)
{
return dotdet(b.x-a.x, b.y-a.y, c.x-a.x, c.y-a.y);
}
int betweenCmp(Point a, Point b, Point c)
{
return dblcmp(dot(a, b, c));
}
/*
参数:
两条线段各自的两个端点
一个指向点Point的指针
返回值:
返回值为0时不相交
返回值为1时规范相交,交点在r中
返回值为2时不规范相交
*/
int segcross(Point a, Point b, Point c, Point d, Point* r)
{
double s1, s2, s3, s4;
int d1, d2, d3, d4;
d1 = dblcmp(s1 = cross(a, b, c));
d2 = dblcmp(s2 = cross(a, b, d));
d3 = dblcmp(s3 = cross(c, d, a));
d4 = dblcmp(s4 = cross(c, d, b));
if ((d1^d2)==-2 && (d3^d4)==-2)
{
r->x = (c.x*s2 - d.x*s1)/(s2 - s1);
r->y = (c.y*s2 - d.y*s1)/(s2 - s1);
return 1;
}
if (d1==0 && betweenCmp(c, a, b)<=0 ||
d2==0 && betweenCmp(d, a, b)<=0 ||
d3==0 && betweenCmp(a, c, d)<=0 ||
d4==0 && betweenCmp(b, c, d)<=0)
return 2;
return 0;
}