View Javadoc

    1   /*
    2    * Licensed to the Apache Software Foundation (ASF) under one or more
    3    * contributor license agreements.  See the NOTICE file distributed with
    4    * this work for additional information regarding copyright ownership.
    5    * The ASF licenses this file to You under the Apache License, Version 2.0
    6    * (the "License"); you may not use this file except in compliance with
    7    * the License.  You may obtain a copy of the License at
    8    *
    9    *      http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  package org.apache.commons.geometry.spherical.twod;
    18
    19  import java.util.Comparator;
    20
    21  import org.apache.commons.geometry.core.Point;
    22  import org.apache.commons.geometry.core.internal.SimpleTupleFormat;
    23  import org.apache.commons.geometry.core.precision.DoublePrecisionContext;
    24  import org.apache.commons.geometry.euclidean.threed.SphericalCoordinates;
    25  import org.apache.commons.geometry.euclidean.threed.Vector3D;
    26  import org.apache.commons.geometry.euclidean.threed.rotation.QuaternionRotation;
    27
    28  /** This class represents a point on the 2-sphere.
    29   * <p>Instances of this class are guaranteed to be immutable.</p>
    30   */
    31  public final class Point2S implements Point<Point2S> {
    32
    33      /** +I (coordinates: ( azimuth = 0, polar = pi/2 )). */
    34      public static final Point2S PLUS_I = new Point2S(0, 0.5 * Math.PI, Vector3D.Unit.PLUS_X);
    35
    36      /** +J (coordinates: ( azimuth = pi/2, polar = pi/2 ))). */
    37      public static final Point2S PLUS_J = new Point2S(0.5 * Math.PI, 0.5 * Math.PI, Vector3D.Unit.PLUS_Y);
    38
    39      /** +K (coordinates: ( azimuth = any angle, polar = 0 )). */
    40      public static final Point2S PLUS_K = new Point2S(0, 0, Vector3D.Unit.PLUS_Z);
    41
    42      /** -I (coordinates: ( azimuth = pi, polar = pi/2 )). */
    43      public static final Point2S MINUS_I = new Point2S(Math.PI, 0.5 * Math.PI, Vector3D.Unit.MINUS_X);
    44
    45      /** -J (coordinates: ( azimuth = 3pi/2, polar = pi/2 )). */
    46      public static final Point2S MINUS_J = new Point2S(1.5 * Math.PI, 0.5 * Math.PI, Vector3D.Unit.MINUS_Y);
    47
    48      /** -K (coordinates: ( azimuth = any angle, polar = pi )). */
    49      public static final Point2S MINUS_K = new Point2S(0, Math.PI, Vector3D.Unit.MINUS_Z);
    50
    51      // CHECKSTYLE: stop ConstantName
    52      /** A point with all coordinates set to NaN. */
    53      public static final Point2S NaN = new Point2S(Double.NaN, Double.NaN, null);
    54      // CHECKSTYLE: resume ConstantName
    55
    56      /** Comparator that sorts points in component-wise ascending order, first sorting
    57       * by polar value and then by azimuth value. Points are only considered equal if
    58       * their components match exactly. Null arguments are evaluated as being greater
    59       * than non-null arguments.
    60       */
    61      public static final Comparator<Point2S> POLAR_AZIMUTH_ASCENDING_ORDER = (a, b) -> {
    62          int cmp = 0;
    63
    64          if (a != null && b != null) {
    65              cmp = Double.compare(a.getPolar(), b.getPolar());
    66
    67              if (cmp == 0) {
    68                  cmp = Double.compare(a.getAzimuth(), b.getAzimuth());
    69              }
    70          } else if (a != null) {
    71              cmp = -1;
    72          } else if (b != null) {
    73              cmp = 1;
    74          }
    75
    76          return cmp;
    77      };
    78      /** Azimuthal angle in the x-y plane. */
    79      private final double azimuth;
    80
    81      /** Polar angle. */
    82      private final double polar;
    83
    84      /** Corresponding 3D normalized vector. */
    85      private final Vector3D.Unit vector;
    86
    87      /** Build a point from its internal components.
    88       * @param azimuth azimuthal angle in the x-y plane
    89       * @param polar polar angle
    90       * @param vector corresponding vector; if null, the vector is computed
    91       */
    92      private Point2S(final double azimuth, final double polar, final Vector3D.Unit vector) {
    93          this.azimuth = SphericalCoordinates.normalizeAzimuth(azimuth);
    94          this.polar = SphericalCoordinates.normalizePolar(polar);
    95          this.vector = (vector != null) ?
    96                  vector :
    97                  computeVector(azimuth, polar);
    98      }
    99
    100     /** Get the azimuth angle in the x-y plane in the range {@code [0, 2pi)}.
    101      * @return azimuth angle in the x-y plane in the range {@code [0, 2pi)}.
    102      * @see Point2S#of(double, double)
    103      */
    104     public double getAzimuth() {
    105         return azimuth;
    106     }
    107
    108     /** Get the polar angle in the range {@code [0, pi)}.
    109      * @return polar angle in the range {@code [0, pi)}.
    110      * @see Point2S#of(double, double)
    111      */
    112     public double getPolar() {
    113         return polar;
    114     }
    115
    116     /** Get the corresponding normalized vector in 3D Euclidean space.
    117      * This value will be null if the spherical coordinates of the point
    118      * are infinite or NaN.
    119      * @return normalized vector
    120      */
    121     public Vector3D.Unit getVector() {
    122         return vector;
    123     }
    124
    125     /** {@inheritDoc} */
    126     @Override
    127     public int getDimension() {
    128         return 2;
    129     }
    130
    131     /** {@inheritDoc} */
    132     @Override
    133     public boolean isNaN() {
    134         return Double.isNaN(azimuth) || Double.isNaN(polar);
    135     }
    136
    137     /** {@inheritDoc} */
    138     @Override
    139     public boolean isInfinite() {
    140         return !isNaN() && (Double.isInfinite(azimuth) || Double.isInfinite(polar));
    141     }
    142
    143     /** {@inheritDoc} */
    144     @Override
    145     public boolean isFinite() {
    146         return Double.isFinite(azimuth) && Double.isFinite(polar);
    147     }
    148
    149     /** Get the point exactly opposite this point on the sphere. The returned
    150      * point is {@code pi} distance away from the current instance.
    151      * @return the point exactly opposite this point on the sphere
    152      */
    153     public Point2S antipodal() {
    154         return from(vector.negate());
    155     }
    156
    157     /** {@inheritDoc} */
    158     @Override
    159     public double distance(final Point2S point) {
    160         return distance(this, point);
    161     }
    162
    163     /** Spherically interpolate a point along the shortest arc between this point and
    164      * the given point. The parameter {@code t} controls the interpolation and is expected
    165      * to be in the range {@code [0, 1]}, with {@code 0} returning a point equivalent to the
    166      * current instance {@code 1} returning a point equivalent to the given instance. If the
    167      * points are antipodal, then an arbitrary arc is chosen from the infinite number available.
    168      * @param other other point to interpolate with
    169      * @param t interpolation parameter
    170      * @return spherically interpolated point
    171      * @see QuaternionRotation#slerp(QuaternionRotation)
    172      * @see QuaternionRotation#createVectorRotation(Vector3D, Vector3D)
    173      */
    174     public Point2S slerp(final Point2S other, final double t) {
    175         final QuaternionRotation start = QuaternionRotation.identity();
    176         final QuaternionRotation end = QuaternionRotation.createVectorRotation(getVector(), other.getVector());
    177
    178         final QuaternionRotation quat = start.slerp(end).apply(t);
    179
    180         return Point2S.from(quat.apply(getVector()));
    181     }
    182
    183     /** Return true if this point should be considered equivalent to the argument using the
    184      * given precision context. This will be true if the distance between the points is
    185      * equivalent to zero as evaluated by the precision context.
    186      * @param point point to compare with
    187      * @param precision precision context used to perform floating point comparisons
    188      * @return true if this point should be considered equivalent to the argument using the
    189      *      given precision context
    190      */
    191     public boolean eq(final Point2S point, final DoublePrecisionContext precision) {
    192         return precision.eqZero(distance(point));
    193     }
    194
    195     /** Get a hashCode for the point.
    196      * .
    197      * <p>All NaN values have the same hash code.</p>
    198      *
    199      * @return a hash code value for this object
    200      */
    201     @Override
    202     public int hashCode() {
    203         if (isNaN()) {
    204             return 542;
    205         }
    206         return 134 * (37 * Double.hashCode(azimuth) +  Double.hashCode(polar));
    207     }
    208
    209     /** Test for the equality of two points.
    210      *
    211      * <p>If all spherical coordinates of two points are exactly the same, and none are
    212      * <code>Double.NaN</code>, the two points are considered to be equal. Note
    213      * that the comparison is made using the azimuth and polar coordinates only; the
    214      * corresponding 3D vectors are not compared. This is significant at the poles,
    215      * where an infinite number of points share the same underlying 3D vector but may
    216      * have different spherical coordinates. For example, the points {@code (0, 0)}
    217      * and {@code (1, 0)} (both located at a pole but with different azimuths) will
    218      * <em>not</em> be considered equal by this method, even though they share the
    219      * exact same underlying 3D vector.</p>
    220      *
    221      * <p>
    222      * <code>NaN</code> coordinates are considered to affect the point globally
    223      * and be equals to each other - i.e, if either (or all) coordinates of the
    224      * point are equal to <code>Double.NaN</code>, the point is equal to
    225      * {@link #NaN}.
    226      * </p>
    227      *
    228      * @param other Object to test for equality to this
    229      * @return true if two points on the 2-sphere objects are exactly equal, false if
    230      *         object is null, not an instance of Point2S, or
    231      *         not equal to this Point2S instance
    232      */
    233     @Override
    234     public boolean equals(final Object other) {
    235         if (this == other) {
    236             return true;
    237         }
    238         if (!(other instanceof Point2S)) {
    239             return false;
    240         }
    241
    242         final Point2S rhs = (Point2S) other;
    243         if (rhs.isNaN()) {
    244             return this.isNaN();
    245         }
    246
    247         return Double.compare(azimuth, rhs.azimuth) == 0 &&
    248                 Double.compare(polar, rhs.polar) == 0;
    249     }
    250
    251     /** {@inheritDoc} */
    252     @Override
    253     public String toString() {
    254         return SimpleTupleFormat.getDefault().format(getAzimuth(), getPolar());
    255     }
    256
    257     /** Build a vector from its spherical coordinates.
    258      * @param azimuth azimuthal angle in the x-y plane
    259      * @param polar polar angle
    260      * @return point instance with the given coordinates
    261      * @see #getAzimuth()
    262      * @see #getPolar()
    263      */
    264     public static Point2S of(final double azimuth, final double polar) {
    265         return new Point2S(azimuth, polar, null);
    266     }
    267
    268     /** Build a point from its underlying 3D vector.
    269      * @param vector 3D vector
    270      * @return point instance with the coordinates determined by the given 3D vector
    271      * @exception IllegalStateException if vector norm is zero
    272      */
    273     public static Point2S from(final Vector3D vector) {
    274         final SphericalCoordinates coords = SphericalCoordinates.fromCartesian(vector);
    275
    276         return new Point2S(coords.getAzimuth(), coords.getPolar(), vector.normalize());
    277     }
    278
    279     /** Parses the given string and returns a new point instance. The expected string
    280      * format is the same as that returned by {@link #toString()}.
    281      * @param str the string to parse
    282      * @return point instance represented by the string
    283      * @throws IllegalArgumentException if the given string has an invalid format
    284      */
    285     public static Point2S parse(final String str) {
    286         return SimpleTupleFormat.getDefault().parse(str, Point2S::of);
    287     }
    288
    289     /** Compute the distance (angular separation) between two points.
    290      * @param p1 first vector
    291      * @param p2 second vector
    292      * @return the angular separation between p1 and p2
    293      */
    294     public static double distance(final Point2S p1, final Point2S p2) {
    295         return p1.vector.angle(p2.vector);
    296     }
    297
    298     /** Compute the 3D Euclidean vector associated with the given spherical coordinates.
    299      * Null is returned if the coordinates are infinite or NaN.
    300      * @param azimuth azimuth value
    301      * @param polar polar value
    302      * @return the 3D Euclidean vector associated with the given spherical coordinates
    303      *      or null if either of the arguments are infinite or NaN.
    304      */
    305     private static Vector3D.Unit computeVector(final double azimuth, final double polar) {
    306         if (Double.isFinite(azimuth) && Double.isFinite(polar)) {
    307             return SphericalCoordinates.toCartesian(1, azimuth, polar).normalize();
    308         }
    309         return null;
    310     }
    311 }