home *** CD-ROM | disk | FTP | other *** search
- package java.awt;
-
- public class Polygon {
- public int npoints;
- public int[] xpoints = new int[4];
- public int[] ypoints = new int[4];
- Rectangle bounds;
-
- public Polygon() {
- }
-
- public Polygon(int[] xpoints, int[] ypoints, int npoints) {
- this.npoints = npoints;
- this.xpoints = new int[npoints];
- this.ypoints = new int[npoints];
- System.arraycopy(xpoints, 0, this.xpoints, 0, npoints);
- System.arraycopy(ypoints, 0, this.ypoints, 0, npoints);
- }
-
- void calculateBounds(int[] xpoints, int[] ypoints, int npoints) {
- int boundsMinX = Integer.MAX_VALUE;
- int boundsMinY = Integer.MAX_VALUE;
- int boundsMaxX = Integer.MIN_VALUE;
- int boundsMaxY = Integer.MIN_VALUE;
-
- for(int i = 0; i < npoints; ++i) {
- int x = xpoints[i];
- boundsMinX = Math.min(boundsMinX, x);
- boundsMaxX = Math.max(boundsMaxX, x);
- int y = ypoints[i];
- boundsMinY = Math.min(boundsMinY, y);
- boundsMaxY = Math.max(boundsMaxY, y);
- }
-
- this.bounds = new Rectangle(boundsMinX, boundsMinY, boundsMaxX - boundsMinX, boundsMaxY - boundsMinY);
- }
-
- void updateBounds(int x, int y) {
- this.bounds.x = Math.min(this.bounds.x, x);
- this.bounds.width = Math.max(this.bounds.width, x - this.bounds.x);
- this.bounds.y = Math.min(this.bounds.y, y);
- this.bounds.height = Math.max(this.bounds.height, y - this.bounds.y);
- }
-
- public void addPoint(int x, int y) {
- if (this.npoints == this.xpoints.length) {
- int[] tmp = new int[this.npoints * 2];
- System.arraycopy(this.xpoints, 0, tmp, 0, this.npoints);
- this.xpoints = tmp;
- tmp = new int[this.npoints * 2];
- System.arraycopy(this.ypoints, 0, tmp, 0, this.npoints);
- this.ypoints = tmp;
- }
-
- this.xpoints[this.npoints] = x;
- this.ypoints[this.npoints] = y;
- ++this.npoints;
- if (this.bounds != null) {
- this.updateBounds(x, y);
- }
-
- }
-
- public Rectangle getBoundingBox() {
- if (this.bounds == null) {
- this.calculateBounds(this.xpoints, this.ypoints, this.npoints);
- }
-
- return this.bounds;
- }
-
- public boolean inside(int x, int y) {
- if (this.getBoundingBox().inside(x, y)) {
- int hits = 0;
-
- for(int i = 0; i < this.npoints; ++i) {
- int j = (i + 1) % this.npoints;
- int dx = this.xpoints[j] - this.xpoints[i];
- int dy = this.ypoints[j] - this.ypoints[i];
- if (dy != 0) {
- int rx = x - this.xpoints[i];
- int ry = y - this.ypoints[i];
- if (this.ypoints[i] == y) {
- --ry;
- }
-
- if (this.ypoints[j] == y) {
- ++dy;
- }
-
- float s = (float)ry / (float)dy;
- if ((double)s >= (double)0.0F && (double)s <= (double)1.0F && (int)(s * (float)dx) > rx) {
- ++hits;
- }
- }
- }
-
- if (hits % 2 == 0) {
- return false;
- } else {
- return true;
- }
- } else {
- return false;
- }
- }
- }
-