Sanibonani =)
I have an array of n unsorted points (x,y,z).
These vertices will create a !convex! polygon.
Now I need your help to create an indexlist of these vertices in a sorted way:
Example:
5 points in 3d space: ( A , B , D , C )
connect them in the unsorted order as they are:
Code:
A------B
\ /
\ /
\/
/\
/ \
/ \
C------D
now sort them (counter-)clock wise:
and connect them again: ( A , B , C , D )
Code:
A------B
| |
| |
| |
| |
| |
| |
C------D
I am currently going over a dotProduct from the center of the polygon, but stucked there...
Maybe arcTan( x / y ) works!?
PHP Code:
sortVertsOnPoly( verts , center )
{
dots = [];
idx = [];
for( i = 0 ; i < verts.size ; i++ )
{
v1 = verts[i]; //catch current vert
v2 = verts[( i + 1 ) % verts.size]; //catch next vert to compare to
v1 -= center; //calculate current directions
v2 -= center;
dots[i] = ( v1[0] * v2[1] - v1[1] * v2[0] ); //calculate the dot(2D)
idx[i] = i; //store the index-information in a different array
}
//sort them by their dot-value
for( i = dots.size ; i > 1 ; i-- )
{
for( j = 0 ; j < i - 1 ; j++ )
{
if( dots[i] > dots[i + 1] )
{
t = dots[i]; //swap
dots[i] = dots[i + 1];
dots[i + 1] = t;
t = idx[i]; //also swap the index array
idx[i] = idx[i + 1];
idx[i + 1] = t;
}
}
}
return idx; //return sorted index array
}
EDIT:
or just get vertex #1 as reference and calculate all other angles and compare them:
guess this woll work also... geez, why i didnt get this in my first toughts?!
PHP Code:
dirs = [];
dirs[0] = 0;
dir = vectorNormalize( verts[0] - center );
for( i = 1 ; i < verts.size ; i++ )
{
dirs[i] = aCos( vectorDot( dir , vectorNormalize( verts[i] - center ) ) );
idx[i] = i;
}
EDIT: dont mind, im confused, the dot is the almost angle ~.~