Slick Forumshttp://slick.ninjacave.com/forum/ Enhancement: Polygon inner /outer face AKA winding orderhttp://slick.ninjacave.com/forum/viewtopic.php?f=9&t=2499 Page 1 of 1

 Author: NickZA [ Wed May 26, 2010 2:06 pm ] Post subject: Enhancement: Polygon inner /outer face AKA winding order For the purposes of unit testing dynamically generated polygonal geometries, I needed to determine whether a given set of vertices used to create a Polygon would provide an inner or outer face polygon... or if you wish to think of it this way, "clockwise" / "anticlockwise" (I put these in quotes for the reason given in Polygon's class description). As it turns out I'm also using Paul Bourke's general polygon area algorithm, which is exactly what is used internally in Polygon.getArea(); however, that method returns the absolute value rather than the signed area value, which is a pity as if it were not so, then the method I give here would not be necessary, as the sign is what allows us to determine the winding order. Rather than subclassing as I've done here, this method can simply be put into net.phys2d.raw.shapes.Polygon itself. Code:package net.handcraftedgames.stoneguard;import net.phys2d.math.ROVector2f;import net.phys2d.math.Vector2f;import net.phys2d.raw.shapes.Polygon;import net.phys2d.math.MathUtil;public class SmartPolygon extends Polygon{   public SmartPolygon()   {      super();   }   public SmartPolygon(ROVector2f[] arg0)   {      super(arg0);   }      /**    * Determines whether a polygon is an inner or an outer face polygon.    * This is done by checking the winding order of its vertices.    *     * @param useScreenCoords Whether the coordinate system uses a downward-    * pointing positive y-axis.    *      * @return True if y-axis points down and vertices are clockwise, or if y-axis    * points up and vertices are counterclockwise; otherwise, false.    */   public boolean isInnerFace(boolean useScreenCoords) throws Exception   {      int numVertices = this.getVertices().length;      ROVector2f[] vertices = this.getVertices();      Vector2f vert, nextVert;      //use sign of polygon area to determine result      float a = 0;      for (int i = 0; i < numVertices; i++)      {         vert = (Vector2f) vertices[i];         nextVert = (Vector2f) vertices[(i+1)%(numVertices)];         a += vert.x*nextVert.y - nextVert.x*vert.y;       }      a *= 0.5;            //check our area with sign:      //System.out.println("area = "+a);      //also Paul Bourke's area sum, however the sign is stripped out in the method call:      //System.out.println(this.getArea());            boolean result = a > 0;      if (!useScreenCoords)         result = !result;            return result;   }}