package MapEditor;
import javax.vecmath.*;
/**
This class represents planar polygons.
Datatype Invariant: m_vertices.length >= 3
*/
public class Polygon
{
/** The vertices of the polygon */
private Point3d[] m_vertices = new Point3d[] {};
/** The normal to the polygon */
private Vector3d m_normal = new Vector3d();
/**
Constructs a Polygon from an array of vertices.
Notes:
- Semantic constraint - The array of vertices must specify a planar polygon.
@param vertices The array of vertices
@throws java.lang.NullPointerException If the vertex array is null
*/
public Polygon(Point3d[] vertices)
{
if(vertices == null) throw new NullPointerException();
m_vertices = vertices;
calculate_normal();
}
/**
Calculates the polygon's normal.
Notes:
- We assume that the polygon is planar. If it is not, this will calculate the normal of the triangle
specified by the first three vertices instead. If that situation arises, we have major problems anyway.
*/
public void calculate_normal()
{
Vector3d l = new Vector3d(m_vertices[1]), r = new Vector3d(m_vertices[2]);
l.sub(m_vertices[0]); // l = v1-v0
r.sub(m_vertices[0]); // r = v2-v0
m_normal.cross(l,r);
m_normal.normalize();
}
/**
Flips the winding order of the polygon's vertices.
*/
public void flip_winding()
{
// Reverse the vertex array.
int l = 0, r = m_vertices.length-1;
while(l < r)
{
Point3d temp = m_vertices[l];
m_vertices[l] = m_vertices[r];
m_vertices[r] = temp;
++l; --r;
}
// The normal will now point in the opposite direction.
m_normal.scale(-1);
}
/**
Gets the polygon's normal.
@return ...think about it...
*/
public Vector3d get_normal()
{
return m_normal;
}
/**
Gets the polygon's vertices.
@return ...think about it...
*/
public Point3d[] get_vertices()
{
return m_vertices;
}
}