bool intersection(Vec2d P0a, Vec2d P0b, Vec2d P1a, Vec2d P1b, Vec2d &result){
float M0= (P0b.y - P0a.y)/(P0b.x- P0a.x);// slope0 = dy/dx
float M1= (P1b.y - P1a.y)/(P1b.x- P1a.x);// slope1 = dy/dx
float X = P1a.y - P0a.y - P1a.x*M1+P0a.x*M0; // y1-y0 - x1*m1 + x0*m0
X/= (M0-M1);
float Y= P0a.y +(X-P0a.x)*M0;
float left0= min(P0a.x, P0b.x);
float right0 = max(P0a.x, P0b.x);
float left1= min(P1a.x, P1b.x);
float right1 = max(P1a.x, P1b.x);
if ( X> left0 && X< right0 && X> left1 && X< right1)
{
result.x=X;
result.y=Y;
//glRectf(X-4,Y-4,X+4,Y+4);
return true;
}
else{
//glRectf(X-4,Y-4,X+4,Y+4);
return false;
}
}
void detectIntersection(){
glBegin(GL_LINE_STRIP);
for(int i=1; i<numPoint; i++){
Vec2d A= pointList[i];
glColor3f(1, 0,0);
glVertex2f(A.x, A.y);
}
glEnd();
for(int i=1; i<numPoint; i++){
Vec2d A= pointList[i];
Vec2d B= pointList[i-1];
for( int j=1; j<numPoint; j++){
if(i==j)
continue;
Vec2d C= pointList[j];
Vec2d D= pointList[j-1];
Vec2d result;
//intersection(A,B,C,D, result);
if(intersection(A,B,C,D, result)){
//something
glColor3f(1, 0,1);
//glBegin(GL_LINE_STRIP);
// glVertex2f(result.x, result.y);
glRectf(result.x-4,result.y-4,result.x+4,result.y+4);
// glEnd();
}
}
}
}
