View Javadoc
1   package org.djutils.draw.bounds;
2   
3   import java.awt.geom.Rectangle2D;
4   import java.util.Arrays;
5   import java.util.Collection;
6   import java.util.Iterator;
7   import java.util.Locale;
8   
9   import org.djutils.draw.Drawable2d;
10  import org.djutils.draw.point.Point2d;
11  import org.djutils.exceptions.Throw;
12  
13  /**
14   * A Bounds2d stores the rectangular 2D bounds of a 2d object, or a collection of 2d objects. The Bounds2d is an immutable
15   * object.
16   * <p>
17   * Copyright (c) 2020-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
18   * BSD-style license. See <a href="https://djutils.org/docs/current/djutils/licenses.html">DJUTILS License</a>.
19   * </p>
20   * @author <a href="https://www.tudelft.nl/averbraeck">Alexander Verbraeck</a>
21   * @author <a href="https://www.tudelft.nl/pknoppers">Peter Knoppers</a>
22   */
23  public class Bounds2d implements Drawable2d, Bounds<Bounds2d, Point2d>
24  {
25      /** */
26      private static final long serialVersionUID = 20200829L;
27  
28      /** The lower bound for x. */
29      private final double minX;
30  
31      /** The lower bound for y. */
32      private final double minY;
33  
34      /** The upper bound for x. */
35      private final double maxX;
36  
37      /** The upper bound for y. */
38      private final double maxY;
39  
40      /**
41       * Construct a Bounds2d by providing its lower and upper bounds in both dimensions.
42       * @param minX double; the lower bound for x
43       * @param maxX double; the upper bound for x
44       * @param minY double; the lower bound for y
45       * @param maxY double; the upper bound for y
46       * @throws IllegalArgumentException when a lower bound is larger than the corresponding upper bound, or any of the bounds is
47       *             NaN
48       */
49      public Bounds2d(final double minX, final double maxX, final double minY, final double maxY) throws IllegalArgumentException
50      {
51          Throw.when(Double.isNaN(minX) || Double.isNaN(maxX) || Double.isNaN(minY) || Double.isNaN(maxY),
52                  IllegalArgumentException.class, "bounds must be numbers (not NaN)");
53          Throw.when(minX > maxX || minY > maxY, IllegalArgumentException.class,
54                  "lower bound for each dimension should be less than or equal to its upper bound");
55          this.minX = minX;
56          this.minY = minY;
57          this.maxX = maxX;
58          this.maxY = maxY;
59      }
60  
61      /**
62       * Constructs a new Bounds2d around the origin (0, 0).
63       * @param deltaX double; the deltaX value around the origin
64       * @param deltaY double; the deltaY value around the origin
65       * @throws IllegalArgumentException when one of the delta values is less than zero
66       */
67      public Bounds2d(final double deltaX, final double deltaY)
68      {
69          this(-0.5 * deltaX, 0.5 * deltaX, -0.5 * deltaY, 0.5 * deltaY);
70      }
71  
72      /**
73       * Construct a Bounds2d from some collection of points, finding the lowest and highest x and y coordinates.
74       * @param points Iterator&lt;? extends Point2d&gt;; Iterator that will generate all the points for which to construct a
75       *            Bounds2d
76       * @throws NullPointerException when points is null
77       * @throws IllegalArgumentException when the iterator provides zero points
78       */
79      public Bounds2d(final Iterator<? extends Point2d> points)
80      {
81          Throw.whenNull(points, "points");
82          Throw.when(!points.hasNext(), IllegalArgumentException.class, "need at least one point");
83          Point2d point = points.next();
84          double tempMinX = point.x;
85          double tempMaxX = point.x;
86          double tempMinY = point.y;
87          double tempMaxY = point.y;
88          while (points.hasNext())
89          {
90              point = points.next();
91              tempMinX = Math.min(tempMinX, point.x);
92              tempMaxX = Math.max(tempMaxX, point.x);
93              tempMinY = Math.min(tempMinY, point.y);
94              tempMaxY = Math.max(tempMaxY, point.y);
95          }
96          this.minX = tempMinX;
97          this.maxX = tempMaxX;
98          this.minY = tempMinY;
99          this.maxY = tempMaxY;
100     }
101 
102     /**
103      * Construct a Bounds2d from an array of Point2d, finding the lowest and highest x and y coordinates.
104      * @param points Point2d[]; the points to construct a Bounds2d from
105      * @throws NullPointerException when points is null
106      * @throws IllegalArgumentException when zero points are provided
107      */
108     public Bounds2d(final Point2d[] points) throws NullPointerException, IllegalArgumentException
109     {
110         this(Arrays.stream(Throw.whenNull(points, "points")).iterator());
111     }
112 
113     /**
114      * Construct a Bounds2d for a Drawable2d.
115      * @param drawable2d Drawable2d; any object that implements the Drawable2d interface
116      * @throws NullPointerException when drawable2d is null
117      */
118     public Bounds2d(final Drawable2d drawable2d) throws NullPointerException
119     {
120         this(Throw.whenNull(drawable2d, "drawable2d").getPoints());
121     }
122 
123     /**
124      * Construct a Bounds2d for several Drawable2d objects.
125      * @param drawable2d Drawable2d...; the Drawable2d objects
126      * @throws NullPointerException when the array is null, or contains a null value
127      * @throws IllegalArgumentException when the length of the array is 0
128      */
129     public Bounds2d(final Drawable2d... drawable2d) throws NullPointerException, IllegalArgumentException
130     {
131         this(pointsOf(drawable2d));
132     }
133 
134     /**
135      * Verify that the array contains at least one entry.
136      * @param drawable2dArray Drawable2d[]; array of Drawable2d objects
137      * @return Drawable2d[]; the array
138      * @throws NullPointerException when the array is null
139      * @throws IllegalArgumentException when the array contains 0 elements
140      */
141     static Drawable2d[] ensureHasOne(final Drawable2d[] drawable2dArray) throws NullPointerException, IllegalArgumentException
142     {
143         Throw.whenNull(drawable2dArray, "drawable2dArray");
144         Throw.when(drawable2dArray.length == 0, IllegalArgumentException.class, "Array must contain at least one value");
145         return drawable2dArray;
146     }
147 
148     /**
149      * Return an iterator that will return all points of one or more Drawable objects.
150      * @param drawable2d Drawable2d...; the Drawable objects
151      * @return Iterator&lt;P&gt;; iterator that will return all points of the Drawable objects
152      * @throws NullPointerException when drawable is null, or contains a null value
153      * @throws IllegalArgumentException when drawable is empty
154      */
155     public static Iterator<Point2d> pointsOf(final Drawable2d... drawable2d)
156     {
157         return new Iterator<Point2d>()
158         {
159             /** Index in the argument array. */
160             private int nextArgument = 0;
161 
162             /** Iterator over the Point2d objects in the current Drawable2d. */
163             private Iterator<? extends Point2d> currentIterator = ensureHasOne(drawable2d)[0].getPoints();
164 
165             @Override
166             public boolean hasNext()
167             {
168                 return this.nextArgument < drawable2d.length - 1 || this.currentIterator.hasNext();
169             }
170 
171             @Override
172             public Point2d next()
173             {
174                 if (this.currentIterator.hasNext())
175                 {
176                     return this.currentIterator.next();
177                 }
178                 // Move to next Drawable2d
179                 this.nextArgument++;
180                 this.currentIterator = drawable2d[this.nextArgument].getPoints();
181                 return this.currentIterator.next(); // Cannot fail because every Drawable has at least one point
182             }
183         };
184     }
185 
186     /**
187      * Construct a Bounds2d for a Collection of Drawable2d objects.
188      * @param drawableCollection Collection&lt;Drawable2d&gt;; the collection
189      * @throws NullPointerException when the collection is null, or contains null values
190      * @throws IllegalArgumentException when the collection is empty
191      */
192     public Bounds2d(final Collection<Drawable2d> drawableCollection) throws NullPointerException, IllegalArgumentException
193     {
194         this(pointsOf(drawableCollection));
195     }
196 
197     /**
198      * Return an iterator that will return all points of one or more Drawable2d objects.
199      * @param drawableCollection Collection&lt;Drawable2d&gt;; the collection of Drawable2d objects
200      * @return Iterator&lt;P&gt;; iterator that will return all points of the Drawable objects
201      * @throws NullPointerException when drawableCollection is null, or contains a null value
202      * @throws IllegalArgumentException when drawableCollection is empty
203      */
204     public static Iterator<Point2d> pointsOf(final Collection<Drawable2d> drawableCollection)
205             throws NullPointerException, IllegalArgumentException
206     {
207         return new Iterator<Point2d>()
208         {
209             /** Iterator that iterates over the collection. */
210             private Iterator<Drawable2d> collectionIterator = ensureHasOne(drawableCollection.iterator());
211 
212             /** Iterator that generates Point2d objects for the currently selected element of the collection. */
213             private Iterator<? extends Point2d> currentIterator = this.collectionIterator.next().getPoints();
214 
215             @Override
216             public boolean hasNext()
217             {
218                 if (this.currentIterator == null)
219                 {
220                     return false;
221                 }
222                 return this.currentIterator.hasNext();
223             }
224 
225             @Override
226             public Point2d next()
227             {
228                 Point2d result = this.currentIterator.next();
229                 if (!this.currentIterator.hasNext())
230                 {
231                     if (this.collectionIterator.hasNext())
232                     {
233                         this.currentIterator = this.collectionIterator.next().getPoints();
234                     }
235                     else
236                     {
237                         this.currentIterator = null;
238                     }
239                 }
240                 return result;
241             }
242         };
243     }
244 
245     /**
246      * Verify that the iterator has something to return.
247      * @param iterator Iterator&lt;Drawable2d&gt;; the iterator
248      * @return Iterator&lt;Drawable2d&gt;; the iterator
249      * @throws NullPointerException when the iterator is null
250      * @throws IllegalArgumentException when the hasNext method of the iterator returns false
251      */
252     public static Iterator<Drawable2d> ensureHasOne(final Iterator<Drawable2d> iterator)
253             throws NullPointerException, IllegalArgumentException
254     {
255         Throw.when(!iterator.hasNext(), IllegalArgumentException.class, "Collection may not be empty");
256         return iterator;
257     }
258 
259     @Override
260     public Iterator<Point2d> getPoints()
261     {
262         Point2d[] array = new Point2d[] {new Point2d(this.minX, this.minY), new Point2d(this.minX, this.maxY),
263                 new Point2d(this.maxX, this.minY), new Point2d(this.maxX, this.maxY)};
264         return Arrays.stream(array).iterator();
265     }
266 
267     @Override
268     public int size()
269     {
270         return 4;
271     }
272 
273     /**
274      * Check if this Bounds2d contains a point. Contains considers a point <b>on</b> the border of this Bounds2d to be outside.
275      * @param x double; the x-coordinate of the point
276      * @param y double; the y-coordinate of the point
277      * @return boolean; whether this Bounds2d contains the point
278      * @throws IllegalArgumentException when any of the coordinates is NaN
279      */
280     public boolean contains(final double x, final double y) throws IllegalArgumentException
281     {
282         Throw.when(Double.isNaN(x) || Double.isNaN(y), IllegalArgumentException.class, "coordinates must be numbers (not NaN)");
283         return x > this.minX && x < this.maxX && y > this.minY && y < this.maxY;
284     }
285 
286     @Override
287     public boolean contains(final Point2d point)
288     {
289         Throw.whenNull(point, "point");
290         return contains(point.x, point.y);
291     }
292 
293     @Override
294     public boolean contains(final Bounds2d otherBounds) throws NullPointerException
295     {
296         Throw.whenNull(otherBounds, "otherBounds");
297         return contains(otherBounds.minX, otherBounds.minY) && contains(otherBounds.maxX, otherBounds.maxY);
298     }
299 
300     /**
301      * Check if this Bounds2d covers a point. Covers returns true when the point is on, or inside this Bounds2d.
302      * @param x double; the x-coordinate of the point
303      * @param y double; the y-coordinate of the point
304      * @return boolean; whether this Bounds2d, including its borders, contains the point
305      */
306     public boolean covers(final double x, final double y)
307     {
308         Throw.when(Double.isNaN(x) || Double.isNaN(y), IllegalArgumentException.class, "coordinates must be numbers (not NaN)");
309         return x >= this.minX && x <= this.maxX && y >= this.minY && y <= this.maxY;
310     }
311 
312     @Override
313     public boolean covers(final Point2d point)
314     {
315         Throw.whenNull(point, "point");
316         return covers(point.x, point.y);
317     }
318 
319     @Override
320     public boolean covers(final Bounds2d otherBounds) throws NullPointerException
321     {
322         Throw.whenNull(otherBounds, "otherBounds");
323         return covers(otherBounds.minX, otherBounds.minY) && covers(otherBounds.maxX, otherBounds.maxY);
324     }
325 
326     @Override
327     public boolean disjoint(final Bounds2d otherBounds) throws NullPointerException
328     {
329         Throw.whenNull(otherBounds, "otherBounds");
330         return otherBounds.minX > this.maxX || otherBounds.maxX < this.minX || otherBounds.minY > this.maxY
331                 || otherBounds.maxY < this.minY;
332     }
333 
334     @Override
335     public boolean intersects(final Bounds2d otherBounds2d) throws NullPointerException
336     {
337         return !disjoint(otherBounds2d);
338     }
339 
340     @Override
341     public Bounds2d intersection(final Bounds2d otherBounds2d)
342     {
343         Throw.whenNull(otherBounds2d, "otherBounds2d");
344         if (disjoint(otherBounds2d))
345         {
346             return null;
347         }
348         return new Bounds2d(Math.max(this.minX, otherBounds2d.minX), Math.min(this.maxX, otherBounds2d.maxX),
349                 Math.max(this.minY, otherBounds2d.minY), Math.min(this.maxY, otherBounds2d.maxY));
350     }
351 
352     /**
353      * Return an AWT Rectangle2D that covers the same area as this Bounds2d.
354      * @return Rectangle2D; the rectangle that covers the same area as this Bounds2d
355      */
356     public Rectangle2D toRectangle2D()
357     {
358         return new Rectangle2D.Double(this.minX, this.minY, this.maxX - this.minX, this.maxY - this.minY);
359     }
360 
361     @Override
362     public double getMinX()
363     {
364         return this.minX;
365     }
366 
367     @Override
368     public double getMaxX()
369     {
370         return this.maxX;
371     }
372 
373     @Override
374     public double getMinY()
375     {
376         return this.minY;
377     }
378 
379     @Override
380     public double getMaxY()
381     {
382         return this.maxY;
383     }
384 
385     @Override
386     public Point2d midPoint()
387     {
388         return new Point2d((this.minX + this.maxX) / 2, (this.minY + this.maxY) / 2);
389     }
390 
391     /**
392      * Return the area of this Bounds2d.
393      * @return double; the area of this Bounds2d
394      */
395     public double getArea()
396     {
397         return getDeltaX() * getDeltaY();
398     }
399 
400     @Override
401     public Bounds2d getBounds()
402     {
403         return this;
404     }
405 
406     @Override
407     public String toString()
408     {
409         return toString("%f");
410     }
411 
412     @Override
413     public String toString(final String doubleFormat, final boolean doNotIncludeClassName)
414     {
415         String format =
416                 String.format("%1$s[x[%2$s : %2$s], y[%2$s : %2$s]]", doNotIncludeClassName ? "" : "Bounds2d ", doubleFormat);
417         return String.format(Locale.US, format, this.minX, this.maxX, this.minY, this.maxY);
418     }
419 
420     @Override
421     public int hashCode()
422     {
423         final int prime = 31;
424         int result = 1;
425         long temp;
426         temp = Double.doubleToLongBits(this.maxX);
427         result = prime * result + (int) (temp ^ (temp >>> 32));
428         temp = Double.doubleToLongBits(this.maxY);
429         result = prime * result + (int) (temp ^ (temp >>> 32));
430         temp = Double.doubleToLongBits(this.minX);
431         result = prime * result + (int) (temp ^ (temp >>> 32));
432         temp = Double.doubleToLongBits(this.minY);
433         result = prime * result + (int) (temp ^ (temp >>> 32));
434         return result;
435     }
436 
437     @SuppressWarnings("checkstyle:needbraces")
438     @Override
439     public boolean equals(final Object obj)
440     {
441         if (this == obj)
442             return true;
443         if (obj == null)
444             return false;
445         if (getClass() != obj.getClass())
446             return false;
447         Bounds2d other = (Bounds2d) obj;
448         if (Double.doubleToLongBits(this.maxX) != Double.doubleToLongBits(other.maxX))
449             return false;
450         if (Double.doubleToLongBits(this.maxY) != Double.doubleToLongBits(other.maxY))
451             return false;
452         if (Double.doubleToLongBits(this.minX) != Double.doubleToLongBits(other.minX))
453             return false;
454         if (Double.doubleToLongBits(this.minY) != Double.doubleToLongBits(other.minY))
455             return false;
456         return true;
457     }
458 
459 }