importjava.util.ArrayList;
importjava.util.List;
/**
*
*
* 2012-5-25下午4:37:31
*/
publicclassSystemTaskJob{
doubleINFINITY= 1e10;
doubleESP= 1e-5;
intMAX_N= 1000;
ListPolygon;
//计算叉乘|P0P1| × |P0P2|
doubleMultiply(Point p1,Point p2, Point p0){
return( (p1.x- p0.x) * (p2.y- p0.y) - (p2.x- p0.x) * (p1.y- p0.y) );
}
//判断线段是否包含点point
privatebooleanIsOnline(Point point,LineSegment line)
{
return( ( Math.abs(Multiply(line.pt1, line.pt2, point))
( ( point.x- line.pt1.x) * ( point.x- line.pt2.x) <= 0 ) &&
( ( point.y- line.pt1.y) * ( point.y- line.pt2.y) <= 0 ) );
}
//判断线段相交
privatebooleanIntersect(LineSegmentL1, LineSegment L2)
{
return( (Math.max(L1.pt1.x, L1.pt2.x) >= Math.min(L2.pt1.x, L2.pt2.x)) &&
(Math.max(L2.pt1.x, L2.pt2.x) >= Math.min(L1.pt1.x, L1.pt2.x)) &&
(Math.max(L1.pt1.y, L1.pt2.y) >= Math.min(L2.pt1.y, L2.pt2.y)) &&
(Math.max(L2.pt1.y, L2.pt2.y) >= Math.min(L1.pt1.y, L1.pt2.y)) &&
(Multiply(L2.pt1, L1.pt2, L1.pt1) * Multiply(L1.pt2, L2.pt2, L1.pt1) >= 0) &&
(Multiply(L1.pt1, L2.pt2, L2.pt1) * Multiply(L2.pt2, L1.pt2, L2.pt1) >= 0)
);
}
/*射线法判断点q与多边形polygon的位置关系,要求polygon为简单多边形,顶点逆时针排列
如果点在多边形内:返回0
如果点在多边形边上:返回1
如果点在多边形外:返回2
*/
publicintInPolygon(List polygon, Point point)
{
intn = polygon.size();
intcount = 0;
LineSegment line = newLineSegment();
line.pt1= point;
line.pt2.y= point.y;
line.pt2.x= -INFINITY;
for(inti = 0; i < n; i++ ) {
//得到多边形的一条边
LineSegment side = newLineSegment();
side.pt1= polygon.get(i);
side.pt2= polygon.get((i + 1) % n);
if( IsOnline(point, side) ) {
return1 ;
}
//如果side平行x轴则不作考虑
if( Math.abs(side.pt1.y- side.pt2.y)
continue;
}
if( IsOnline(side.pt1, line) ) {
if( side.pt1.y> side.pt2.y) count++;
} elseif( IsOnline(side.pt2, line) ) {
if( side.pt2.y> side.pt1.y) count++;
} elseif( Intersect(line, side) ) {
count++;
}
}
if( count % 2 == 1 )
{
return0;
}
else
{
return2;
}
}
publicstaticvoidmain(String[] args)
{
SystemTaskJob systemTaskJob = newSystemTaskJob();
List polygon = newArrayList();
Point point1 = newPoint(4,9);
Point point2 = newPoint(7,10);
Pointpoint3 = newPoint(8,2);
Point point4 = newPoint(6,8);
Point point5 = newPoint(6,9);
Point checkpoint = newPoint(7,11);
polygon.add(point1);
polygon.add(point2);
polygon.add(point3);
polygon.add(point4);
polygon.add(point5);
intm = systemTaskJob.InPolygon(polygon, checkpoint);
System.out.println("========="+m);
}
}
classPoint
{
publicdoublex;
publicdoubley;
publicPoint()
{}
publicPoint(doublex,doubley)
{
this.x=x;
this.y=y;
}
}
classLineSegment
{
publicPointpt1;
publicPointpt2;
publicLineSegment()
{
this.pt1=newPoint();
this.pt2=newPoint();
}
}