Programically determine vertex clockwise/counter clockwise?

Hi everyone,

I've been using Box2d in a few projects, and have written a graphical Java-based editor to help me create models and shapes.

Problem is when I create edgechain shapes I inevitably end up with the vertices in the wrong order, and my other objects pass through their edges and get stuck inside the edgechain shape. I picked up by reading the forums that shape vertices must be defined in clockwise order, and edgeshapes must be defined in counter clockwise order.

Does anyone know a programmatic way to determine if the vertices are in the correct order?

Thanks!
I haven't used that version of Box2D, so I can't comment directly on the 'edge chain' issue. As for programatically determining the winding order though, that can be done using the 'perp-dot' product, which is usually defined as:

Code:
perp_dot(a, b) = -a.y * bx + ax * by

Although it can be defined the other way around as well.

Given two line segments that share a vertex, you can use the perp-dot product to determine whether the second line 'turns left or right' relative to the first, e.g.:

Code:
float d = perp_dot(B - A, C - B);
if (d < 0) {
    return RIGHT;
} else {
    return LEFT;
}


Note that I'm ignoring the collinear case here (which usually needs special handling due to the limits of numerical precision).

By computing the relative direction for each pair of consecutive edges in the loop, you can determine whether the loop is non-convex (a mix of left and right turns) or convex (all turns in the same direction), and for convex loops, whether the loop is wound CCW or CW (all left turns for CCW and all right turns for CW, assuming a standard Cartesian coordinate system).
Wow, THANK YOU!! That's exactly what I was hoping for 🙂

Original thread: https://box2d.org/forum/viewtopic.php?t=4462