PageRenderTime 20ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/java/awt/Polygon.java

https://github.com/penberg/classpath
Java | 611 lines | 280 code | 47 blank | 284 comment | 70 complexity | da972527262a08b02acebd1f2ed8134b MD5 | raw file
  1. /* Polygon.java -- class representing a polygon
  2. Copyright (C) 1999, 2002, 2004, 2005 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.awt;
  32. import java.awt.geom.AffineTransform;
  33. import java.awt.geom.Line2D;
  34. import java.awt.geom.PathIterator;
  35. import java.awt.geom.Point2D;
  36. import java.awt.geom.Rectangle2D;
  37. import java.io.Serializable;
  38. /**
  39. * This class represents a polygon, a closed, two-dimensional region in a
  40. * coordinate space. The region is bounded by an arbitrary number of line
  41. * segments, between (x,y) coordinate vertices. The polygon has even-odd
  42. * winding, meaning that a point is inside the shape if it crosses the
  43. * boundary an odd number of times on the way to infinity.
  44. *
  45. * <p>There are some public fields; if you mess with them in an inconsistent
  46. * manner, it is your own fault when you get NullPointerException,
  47. * ArrayIndexOutOfBoundsException, or invalid results. Also, this class is
  48. * not threadsafe.
  49. *
  50. * @author Aaron M. Renn (arenn@urbanophile.com)
  51. * @author Eric Blake (ebb9@email.byu.edu)
  52. * @since 1.0
  53. * @status updated to 1.4
  54. */
  55. public class Polygon implements Shape, Serializable
  56. {
  57. /**
  58. * Compatible with JDK 1.0+.
  59. */
  60. private static final long serialVersionUID = -6460061437900069969L;
  61. /**
  62. * This total number of endpoints.
  63. *
  64. * @serial the number of endpoints, possibly less than the array sizes
  65. */
  66. public int npoints;
  67. /**
  68. * The array of X coordinates of endpoints. This should not be null.
  69. *
  70. * @see #addPoint(int, int)
  71. * @serial the x coordinates
  72. */
  73. public int[] xpoints;
  74. /**
  75. * The array of Y coordinates of endpoints. This should not be null.
  76. *
  77. * @see #addPoint(int, int)
  78. * @serial the y coordinates
  79. */
  80. public int[] ypoints;
  81. /**
  82. * The bounding box of this polygon. This is lazily created and cached, so
  83. * it must be invalidated after changing points.
  84. *
  85. * @see #getBounds()
  86. * @serial the bounding box, or null
  87. */
  88. protected Rectangle bounds;
  89. /** A big number, but not so big it can't survive a few float operations */
  90. private static final double BIG_VALUE = java.lang.Double.MAX_VALUE / 10.0;
  91. /**
  92. * Initializes an empty polygon.
  93. */
  94. public Polygon()
  95. {
  96. // Leave room for growth.
  97. xpoints = new int[4];
  98. ypoints = new int[4];
  99. }
  100. /**
  101. * Create a new polygon with the specified endpoints. The arrays are copied,
  102. * so that future modifications to the parameters do not affect the polygon.
  103. *
  104. * @param xpoints the array of X coordinates for this polygon
  105. * @param ypoints the array of Y coordinates for this polygon
  106. * @param npoints the total number of endpoints in this polygon
  107. * @throws NegativeArraySizeException if npoints is negative
  108. * @throws IndexOutOfBoundsException if npoints exceeds either array
  109. * @throws NullPointerException if xpoints or ypoints is null
  110. */
  111. public Polygon(int[] xpoints, int[] ypoints, int npoints)
  112. {
  113. this.xpoints = new int[npoints];
  114. this.ypoints = new int[npoints];
  115. System.arraycopy(xpoints, 0, this.xpoints, 0, npoints);
  116. System.arraycopy(ypoints, 0, this.ypoints, 0, npoints);
  117. this.npoints = npoints;
  118. }
  119. /**
  120. * Reset the polygon to be empty. The arrays are left alone, to avoid object
  121. * allocation, but the number of points is set to 0, and all cached data
  122. * is discarded. If you are discarding a huge number of points, it may be
  123. * more efficient to just create a new Polygon.
  124. *
  125. * @see #invalidate()
  126. * @since 1.4
  127. */
  128. public void reset()
  129. {
  130. npoints = 0;
  131. invalidate();
  132. }
  133. /**
  134. * Invalidate or flush all cached data. After direct manipulation of the
  135. * public member fields, this is necessary to avoid inconsistent results
  136. * in methods like <code>contains</code>.
  137. *
  138. * @see #getBounds()
  139. * @since 1.4
  140. */
  141. public void invalidate()
  142. {
  143. bounds = null;
  144. }
  145. /**
  146. * Translates the polygon by adding the specified values to all X and Y
  147. * coordinates. This updates the bounding box, if it has been calculated.
  148. *
  149. * @param dx the amount to add to all X coordinates
  150. * @param dy the amount to add to all Y coordinates
  151. * @since 1.1
  152. */
  153. public void translate(int dx, int dy)
  154. {
  155. int i = npoints;
  156. while (--i >= 0)
  157. {
  158. xpoints[i] += dx;
  159. ypoints[i] += dy;
  160. }
  161. if (bounds != null)
  162. {
  163. bounds.x += dx;
  164. bounds.y += dy;
  165. }
  166. }
  167. /**
  168. * Adds the specified endpoint to the polygon. This updates the bounding
  169. * box, if it has been created.
  170. *
  171. * @param x the X coordinate of the point to add
  172. * @param y the Y coordiante of the point to add
  173. */
  174. public void addPoint(int x, int y)
  175. {
  176. if (npoints + 1 > xpoints.length)
  177. {
  178. int[] newx = new int[npoints + 1];
  179. System.arraycopy(xpoints, 0, newx, 0, npoints);
  180. xpoints = newx;
  181. }
  182. if (npoints + 1 > ypoints.length)
  183. {
  184. int[] newy = new int[npoints + 1];
  185. System.arraycopy(ypoints, 0, newy, 0, npoints);
  186. ypoints = newy;
  187. }
  188. xpoints[npoints] = x;
  189. ypoints[npoints] = y;
  190. npoints++;
  191. if (bounds != null)
  192. {
  193. if (npoints == 1)
  194. {
  195. bounds.x = x;
  196. bounds.y = y;
  197. }
  198. else
  199. {
  200. if (x < bounds.x)
  201. {
  202. bounds.width += bounds.x - x;
  203. bounds.x = x;
  204. }
  205. else if (x > bounds.x + bounds.width)
  206. bounds.width = x - bounds.x;
  207. if (y < bounds.y)
  208. {
  209. bounds.height += bounds.y - y;
  210. bounds.y = y;
  211. }
  212. else if (y > bounds.y + bounds.height)
  213. bounds.height = y - bounds.y;
  214. }
  215. }
  216. }
  217. /**
  218. * Returns the bounding box of this polygon. This is the smallest
  219. * rectangle with sides parallel to the X axis that will contain this
  220. * polygon.
  221. *
  222. * @return the bounding box for this polygon
  223. * @see #getBounds2D()
  224. * @since 1.1
  225. */
  226. public Rectangle getBounds()
  227. {
  228. return getBoundingBox();
  229. }
  230. /**
  231. * Returns the bounding box of this polygon. This is the smallest
  232. * rectangle with sides parallel to the X axis that will contain this
  233. * polygon.
  234. *
  235. * @return the bounding box for this polygon
  236. * @see #getBounds2D()
  237. * @deprecated use {@link #getBounds()} instead
  238. */
  239. public Rectangle getBoundingBox()
  240. {
  241. if (bounds == null)
  242. {
  243. if (npoints == 0)
  244. return bounds = new Rectangle();
  245. int i = npoints - 1;
  246. int minx = xpoints[i];
  247. int maxx = minx;
  248. int miny = ypoints[i];
  249. int maxy = miny;
  250. while (--i >= 0)
  251. {
  252. int x = xpoints[i];
  253. int y = ypoints[i];
  254. if (x < minx)
  255. minx = x;
  256. else if (x > maxx)
  257. maxx = x;
  258. if (y < miny)
  259. miny = y;
  260. else if (y > maxy)
  261. maxy = y;
  262. }
  263. bounds = new Rectangle(minx, miny, maxx - minx, maxy - miny);
  264. }
  265. return bounds;
  266. }
  267. /**
  268. * Tests whether or not the specified point is inside this polygon.
  269. *
  270. * @param p the point to test
  271. * @return true if the point is inside this polygon
  272. * @throws NullPointerException if p is null
  273. * @see #contains(double, double)
  274. */
  275. public boolean contains(Point p)
  276. {
  277. return contains(p.getX(), p.getY());
  278. }
  279. /**
  280. * Tests whether or not the specified point is inside this polygon.
  281. *
  282. * @param x the X coordinate of the point to test
  283. * @param y the Y coordinate of the point to test
  284. * @return true if the point is inside this polygon
  285. * @see #contains(double, double)
  286. * @since 1.1
  287. */
  288. public boolean contains(int x, int y)
  289. {
  290. return contains((double) x, (double) y);
  291. }
  292. /**
  293. * Tests whether or not the specified point is inside this polygon.
  294. *
  295. * @param x the X coordinate of the point to test
  296. * @param y the Y coordinate of the point to test
  297. * @return true if the point is inside this polygon
  298. * @see #contains(double, double)
  299. * @deprecated use {@link #contains(int, int)} instead
  300. */
  301. public boolean inside(int x, int y)
  302. {
  303. return contains((double) x, (double) y);
  304. }
  305. /**
  306. * Returns a high-precision bounding box of this polygon. This is the
  307. * smallest rectangle with sides parallel to the X axis that will contain
  308. * this polygon.
  309. *
  310. * @return the bounding box for this polygon
  311. * @see #getBounds()
  312. * @since 1.2
  313. */
  314. public Rectangle2D getBounds2D()
  315. {
  316. // For polygons, the integer version is exact!
  317. return getBounds();
  318. }
  319. /**
  320. * Tests whether or not the specified point is inside this polygon.
  321. *
  322. * @param x the X coordinate of the point to test
  323. * @param y the Y coordinate of the point to test
  324. * @return true if the point is inside this polygon
  325. * @since 1.2
  326. */
  327. public boolean contains(double x, double y)
  328. {
  329. return ((evaluateCrossings(x, y, false, BIG_VALUE) & 1) != 0);
  330. }
  331. /**
  332. * Tests whether or not the specified point is inside this polygon.
  333. *
  334. * @param p the point to test
  335. * @return true if the point is inside this polygon
  336. * @throws NullPointerException if p is null
  337. * @see #contains(double, double)
  338. * @since 1.2
  339. */
  340. public boolean contains(Point2D p)
  341. {
  342. return contains(p.getX(), p.getY());
  343. }
  344. /**
  345. * Test if a high-precision rectangle intersects the shape. This is true
  346. * if any point in the rectangle is in the shape. This implementation is
  347. * precise.
  348. *
  349. * @param x the x coordinate of the rectangle
  350. * @param y the y coordinate of the rectangle
  351. * @param w the width of the rectangle, treated as point if negative
  352. * @param h the height of the rectangle, treated as point if negative
  353. * @return true if the rectangle intersects this shape
  354. * @since 1.2
  355. */
  356. public boolean intersects(double x, double y, double w, double h)
  357. {
  358. /* Does any edge intersect? */
  359. if (evaluateCrossings(x, y, false, w) != 0 /* top */
  360. || evaluateCrossings(x, y + h, false, w) != 0 /* bottom */
  361. || evaluateCrossings(x + w, y, true, h) != 0 /* right */
  362. || evaluateCrossings(x, y, true, h) != 0) /* left */
  363. return true;
  364. /* No intersections, is any point inside? */
  365. if ((evaluateCrossings(x, y, false, BIG_VALUE) & 1) != 0)
  366. return true;
  367. return false;
  368. }
  369. /**
  370. * Test if a high-precision rectangle intersects the shape. This is true
  371. * if any point in the rectangle is in the shape. This implementation is
  372. * precise.
  373. *
  374. * @param r the rectangle
  375. * @return true if the rectangle intersects this shape
  376. * @throws NullPointerException if r is null
  377. * @see #intersects(double, double, double, double)
  378. * @since 1.2
  379. */
  380. public boolean intersects(Rectangle2D r)
  381. {
  382. return intersects(r.getX(), r.getY(), r.getWidth(), r.getHeight());
  383. }
  384. /**
  385. * Test if a high-precision rectangle lies completely in the shape. This is
  386. * true if all points in the rectangle are in the shape. This implementation
  387. * is precise.
  388. *
  389. * @param x the x coordinate of the rectangle
  390. * @param y the y coordinate of the rectangle
  391. * @param w the width of the rectangle, treated as point if negative
  392. * @param h the height of the rectangle, treated as point if negative
  393. * @return true if the rectangle is contained in this shape
  394. * @since 1.2
  395. */
  396. public boolean contains(double x, double y, double w, double h)
  397. {
  398. if (! getBounds2D().intersects(x, y, w, h))
  399. return false;
  400. /* Does any edge intersect? */
  401. if (evaluateCrossings(x, y, false, w) != 0 /* top */
  402. || evaluateCrossings(x, y + h, false, w) != 0 /* bottom */
  403. || evaluateCrossings(x + w, y, true, h) != 0 /* right */
  404. || evaluateCrossings(x, y, true, h) != 0) /* left */
  405. return false;
  406. /* No intersections, is any point inside? */
  407. if ((evaluateCrossings(x, y, false, BIG_VALUE) & 1) != 0)
  408. return true;
  409. return false;
  410. }
  411. /**
  412. * Test if a high-precision rectangle lies completely in the shape. This is
  413. * true if all points in the rectangle are in the shape. This implementation
  414. * is precise.
  415. *
  416. * @param r the rectangle
  417. * @return true if the rectangle is contained in this shape
  418. * @throws NullPointerException if r is null
  419. * @see #contains(double, double, double, double)
  420. * @since 1.2
  421. */
  422. public boolean contains(Rectangle2D r)
  423. {
  424. return contains(r.getX(), r.getY(), r.getWidth(), r.getHeight());
  425. }
  426. /**
  427. * Return an iterator along the shape boundary. If the optional transform
  428. * is provided, the iterator is transformed accordingly. Each call returns
  429. * a new object, independent from others in use. This class is not
  430. * threadsafe to begin with, so the path iterator is not either.
  431. *
  432. * @param transform an optional transform to apply to the iterator
  433. * @return a new iterator over the boundary
  434. * @since 1.2
  435. */
  436. public PathIterator getPathIterator(final AffineTransform transform)
  437. {
  438. return new PathIterator()
  439. {
  440. /** The current vertex of iteration. */
  441. private int vertex;
  442. public int getWindingRule()
  443. {
  444. return WIND_EVEN_ODD;
  445. }
  446. public boolean isDone()
  447. {
  448. return vertex > npoints;
  449. }
  450. public void next()
  451. {
  452. vertex++;
  453. }
  454. public int currentSegment(float[] coords)
  455. {
  456. if (vertex >= npoints)
  457. return SEG_CLOSE;
  458. coords[0] = xpoints[vertex];
  459. coords[1] = ypoints[vertex];
  460. if (transform != null)
  461. transform.transform(coords, 0, coords, 0, 1);
  462. return vertex == 0 ? SEG_MOVETO : SEG_LINETO;
  463. }
  464. public int currentSegment(double[] coords)
  465. {
  466. if (vertex >= npoints)
  467. return SEG_CLOSE;
  468. coords[0] = xpoints[vertex];
  469. coords[1] = ypoints[vertex];
  470. if (transform != null)
  471. transform.transform(coords, 0, coords, 0, 1);
  472. return vertex == 0 ? SEG_MOVETO : SEG_LINETO;
  473. }
  474. };
  475. }
  476. /**
  477. * Return an iterator along the flattened version of the shape boundary.
  478. * Since polygons are already flat, the flatness parameter is ignored, and
  479. * the resulting iterator only has SEG_MOVETO, SEG_LINETO and SEG_CLOSE
  480. * points. If the optional transform is provided, the iterator is
  481. * transformed accordingly. Each call returns a new object, independent
  482. * from others in use. This class is not threadsafe to begin with, so the
  483. * path iterator is not either.
  484. *
  485. * @param transform an optional transform to apply to the iterator
  486. * @param flatness the maximum distance for deviation from the real boundary
  487. * @return a new iterator over the boundary
  488. * @since 1.2
  489. */
  490. public PathIterator getPathIterator(AffineTransform transform,
  491. double flatness)
  492. {
  493. return getPathIterator(transform);
  494. }
  495. /**
  496. * Helper for contains, intersects, calculates the number of intersections
  497. * between the polygon and a line extending from the point (x, y) along
  498. * the positive X, or Y axis, within a given interval.
  499. *
  500. * @return the winding number.
  501. * @see #contains(double, double)
  502. */
  503. private int evaluateCrossings(double x, double y, boolean useYaxis,
  504. double distance)
  505. {
  506. double x0;
  507. double x1;
  508. double y0;
  509. double y1;
  510. double epsilon = 0.0;
  511. int crossings = 0;
  512. int[] xp;
  513. int[] yp;
  514. if (useYaxis)
  515. {
  516. xp = ypoints;
  517. yp = xpoints;
  518. double swap;
  519. swap = y;
  520. y = x;
  521. x = swap;
  522. }
  523. else
  524. {
  525. xp = xpoints;
  526. yp = ypoints;
  527. }
  528. /* Get a value which is small but not insignificant relative the path. */
  529. epsilon = 1E-7;
  530. x0 = xp[0] - x;
  531. y0 = yp[0] - y;
  532. for (int i = 1; i < npoints; i++)
  533. {
  534. x1 = xp[i] - x;
  535. y1 = yp[i] - y;
  536. if (y0 == 0.0)
  537. y0 -= epsilon;
  538. if (y1 == 0.0)
  539. y1 -= epsilon;
  540. if (y0 * y1 < 0)
  541. if (Line2D.linesIntersect(x0, y0, x1, y1, epsilon, 0.0, distance, 0.0))
  542. ++crossings;
  543. x0 = xp[i] - x;
  544. y0 = yp[i] - y;
  545. }
  546. // end segment
  547. x1 = xp[0] - x;
  548. y1 = yp[0] - y;
  549. if (y0 == 0.0)
  550. y0 -= epsilon;
  551. if (y1 == 0.0)
  552. y1 -= epsilon;
  553. if (y0 * y1 < 0)
  554. if (Line2D.linesIntersect(x0, y0, x1, y1, epsilon, 0.0, distance, 0.0))
  555. ++crossings;
  556. return crossings;
  557. }
  558. } // class Polygon