I once again get hooked to pointless micro performance optimizations but didn’t use as much time for checking the algorithm.
I made quite fast algorithm that check point vs any polygon. But is there way to do this even faster.
public class Bench {
/**
* Checks whether the given point is in the polygon(can be concave). x[] and
* y[] is assumed to be least size of verticesNum
*
* @param x
* array of x coordinates
* @param y
* array of y coordinates
* @param verticesNum
* @param px
* point x coordinate
* @param py
* point y coordinate
* @return Wheter the point is in the polygon
*/
public static boolean isPointInPolygon(float x[], float y[],
int verticesNum, float px, float py) {
if (verticesNum < 3)
return false;
boolean oddNodes = false;
float x2 = x[verticesNum - 1];
float y2 = y[verticesNum - 1];
float x1, y1;
for (int i = 0; i < verticesNum; x2 = x1, y2 = y1, ++i) {
x1 = x[i];
y1 = y[i];
if (((y1 < py) && (y2 >= py))
|| (y1 >= py) && (y2 < py)) {
if ((py - y1) / (y2 - y1)
* (x2 - x1) < (px - x1))
oddNodes = !oddNodes;
}
}
return oddNodes;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int N = 667;
float x[] = new float[N];
float y[] = new float[N];
x[0] = N;
y[0] = 0;
x[1] = 0;
y[1] = 0;
for (int i = 2; i < N; i++) {
x[i] = N;
y[i] = (float) Math.random() * N;
}
boolean t = false;
// warmup
for (int j = 0; j < N; j++) {
t = isPointInPolygon(x, y, N, j, j);
}
long time = System.nanoTime();
for (int j = 0; j < N; j++) {
for (int i = 0; i < N; i++) {
t = isPointInPolygon(x, y, N, j, i);
}
}
System.out.println(t + " time used:"
+ (System.nanoTime() - time)
/ 1000000 + "ms");
}
I allready tried trick that is introduced there http://alienryderflex.com/polygon/ but those didn’t help at all.
This is used for box2dLights to check if given point is inside of any light to query is something in shadows.