// Polygon detection test // Solution 2(2D) from: // http://astronomy.swin.edu.au/~pbourke/geometry/insidepoly/ // theory: given triangles plotted from a point inside a polygon // all the angles at that point from those triangles = 2PI radians float [] points = { 120,20, 242,20, 250,200, 167,150 }; Polygon polys; void setup(){ size(400,400); polys = new Polygon(points); } void draw(){ background(255); fill(255,0,255); if(polys.isInside(mouseX,mouseY)) fill(255,255,0); polys.draw(); } void mousePressed(){ println(mouseX+","+mouseY); polys.addVertex(mouseX,mouseY); } class Polygon{ float [] x,y; Polygon (float [] points){ x = new float[points.length/2]; y = new float[points.length/2]; for(int i = 0; i < points.length; i+=2){ x[i/2] = points[i]; y[i/2] = points[i+1]; } } Polygon (float startX, float startY){ x = new float[1]; y = new float[1]; x[0] = startX; y[0] = startY; } void addVertex(float addX, float addY){ x = append(x, addX); y = append(y, addY); } boolean isInside(float isX, float isY){ float theta = 0.0; for (int i = 1; i < x.length+1; i++) theta += acuteAngle(isX, isY, x[i-1], y[i-1], x[i%x.length], y[i%x.length]); if (abs(theta) < PI) return false; else return true; } void draw(){ beginShape(POLYGON); for(int i = 0; i < x.length; i++) vertex(x[i],y[i]); endShape(); } } float acuteAngle(float x0, float y0, float x1, float y1, float x2, float y2){ float theta0,theta1,dtheta; theta0 = atan2(y0-y1,x0-x1); theta1 = atan2(y0-y2,x0-x2); dtheta = theta1 - theta0; while (dtheta > PI) dtheta -= TWO_PI; while (dtheta < -PI) dtheta += TWO_PI; return dtheta; }