[comp.graphics] CW or CCW in 2d, a better way

woolstar@around.caltech.edu (John Woolverton) (10/23/90)

corkum@csri.toronto.edu (Brent Thomas Corkum) writes:
>This routine and sample program computes whether a 2D polygon is clockwise
>or counter-clockwise. 

>Brent Corkum
>corkum@csri.toronto.edu
   [Extremely complicated function follows]

Luckily there are much easier ways to do this kind of thing.
For the 2D case, one only needs to check the normal vektor and see
if it is pointing up or down to determine clockwise/counter-clockwise:

-------

/******
   Clockwise vs Counterclockwise
   (c) copyright 1990 -- all rights abandoned

   */

typedef struct { double x, y; } point2d;

int     Isclockwise(number, points)
int     number;
point2d *points;
{
   point2d
      *left, *p, *best_point, *right;
   int
      find, count, best;
   double tmp;

   tmp= points-> x, best_point= points, best= 0;
   for (p= points+1, count= 1; (count < number); count++, p++)
   {
      if (p-> x > tmp) continue;
      if (p-> y > best_point-> y) continue;
      tmp= p-> x, best= count, best_point= p;
      }

   left= (best > 0) ? best_point -1 : points +number -1;
   right= (best +1 < number) ? best_point +1 : points;
   /****
      take the cross product
         > 0  counter clockwise
         < 0  clockwise
      */

   tmp= ((right-> x -best_point-> x) * (left-> y -best_point-> y))
      - ((left-> x -best_point-> x) * (right-> y -best_point-> y));

   return (tmp < 0.0);
   }

Lots of optimizations exist for this too, buts this gets
the job done.

	John d Woolverton, Ray Tracing Engineer
	   woolstar@csvax.caltech.edu

"Not responcible for small errors incurred in the short time
 it took to write this."