View Javadoc
1   package nl.tudelft.simulation.language.d2;
2   
3   import java.awt.geom.Point2D;
4   
5   /**
6    * The Circle class presents a number of mathematical utility functions for circles. For now, the class only implements static
7    * helper methods. No instances of the class should be made.
8    * <p>
9    * Copyright (c) 2003-2025 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved. See
10   * for project information <a href="https://simulation.tudelft.nl/dsol/manual/" target="_blank">DSOL Manual</a>. The DSOL
11   * project is distributed under a three-clause BSD-style license, which can be found at
12   * <a href="https://simulation.tudelft.nl/dsol/docs/latest/license.html" target="_blank">DSOL License</a>.
13   * </p>
14   * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
15   */
16  public final class Circle
17  {
18      /**
19       * constructs a new Circle.
20       */
21      private Circle()
22      {
23          // unreachable code
24      }
25  
26      /**
27       * Elegant intersection algorithm from http://astronomy.swin.edu.au/~pbourke/geometry/2circle/.
28       * @param center0 the center of the first circle
29       * @param radius0 the radius of the first circle
30       * @param center1 the center of the second circle
31       * @param radius1 the radius of the second circle
32       * @return the intersection
33       */
34      public static Point2D[] intersection(final Point2D center0, final double radius0, final Point2D center1,
35              final double radius1)
36      {
37          double distance = center0.distance(center1);
38          double x0 = center0.getX();
39          double x1 = center1.getX();
40          double y0 = center0.getY();
41          double y1 = center1.getY();
42          Point2D[] result;
43          if ((distance > radius0 + radius1) || (distance < Math.abs(radius0 - radius1)))
44          {
45              return new Point2D.Double[0];
46          }
47          double a = (radius0 * radius0 - radius1 * radius1 + distance * distance) / (2 * distance);
48          double h = Math.sqrt(radius0 * radius0 - a * a);
49          double x2 = x0 + ((a / distance) * (x1 - x0));
50          double y2 = y0 + ((a / distance) * (y1 - y0));
51          if (distance == radius0 + radius1)
52          {
53              result = new Point2D.Double[1];
54              result[0] = new Point2D.Double(x2, y2);
55          }
56          else
57          {
58              result = new Point2D.Double[2];
59              result[0] = new Point2D.Double(x2 + h * (y1 - y0) / distance, y2 - h * (x1 - x0) / distance);
60              result[1] = new Point2D.Double(x2 - h * (y1 - y0) / distance, y2 + h * (x1 - x0) / distance);
61          }
62          return result;
63      }
64  }