001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.geometry.spherical.twod;
018
019import java.util.Comparator;
020
021import org.apache.commons.geometry.core.Point;
022import org.apache.commons.geometry.core.internal.SimpleTupleFormat;
023import org.apache.commons.geometry.euclidean.threed.SphericalCoordinates;
024import org.apache.commons.geometry.euclidean.threed.Vector3D;
025import org.apache.commons.geometry.euclidean.threed.rotation.QuaternionRotation;
026import org.apache.commons.numbers.core.Precision;
027
028/** This class represents a point on the 2-sphere.
029 * <p>Instances of this class are guaranteed to be immutable.</p>
030 */
031public final class Point2S implements Point<Point2S> {
032
033    /** +I (coordinates: ( azimuth = 0, polar = pi/2 )). */
034    public static final Point2S PLUS_I = new Point2S(0, 0.5 * Math.PI, Vector3D.Unit.PLUS_X);
035
036    /** +J (coordinates: ( azimuth = pi/2, polar = pi/2 ))). */
037    public static final Point2S PLUS_J = new Point2S(0.5 * Math.PI, 0.5 * Math.PI, Vector3D.Unit.PLUS_Y);
038
039    /** +K (coordinates: ( azimuth = any angle, polar = 0 )). */
040    public static final Point2S PLUS_K = new Point2S(0, 0, Vector3D.Unit.PLUS_Z);
041
042    /** -I (coordinates: ( azimuth = pi, polar = pi/2 )). */
043    public static final Point2S MINUS_I = new Point2S(Math.PI, 0.5 * Math.PI, Vector3D.Unit.MINUS_X);
044
045    /** -J (coordinates: ( azimuth = 3pi/2, polar = pi/2 )). */
046    public static final Point2S MINUS_J = new Point2S(1.5 * Math.PI, 0.5 * Math.PI, Vector3D.Unit.MINUS_Y);
047
048    /** -K (coordinates: ( azimuth = any angle, polar = pi )). */
049    public static final Point2S MINUS_K = new Point2S(0, Math.PI, Vector3D.Unit.MINUS_Z);
050
051    /** A point with all coordinates set to NaN. */
052    public static final Point2S NaN = new Point2S(Double.NaN, Double.NaN, null);
053
054    /** Comparator that sorts points in component-wise ascending order, first sorting
055     * by polar value and then by azimuth value. Points are only considered equal if
056     * their components match exactly. Null arguments are evaluated as being greater
057     * than non-null arguments.
058     */
059    public static final Comparator<Point2S> POLAR_AZIMUTH_ASCENDING_ORDER = (a, b) -> {
060        int cmp = 0;
061
062        if (a != null && b != null) {
063            cmp = Double.compare(a.getPolar(), b.getPolar());
064
065            if (cmp == 0) {
066                cmp = Double.compare(a.getAzimuth(), b.getAzimuth());
067            }
068        } else if (a != null) {
069            cmp = -1;
070        } else if (b != null) {
071            cmp = 1;
072        }
073
074        return cmp;
075    };
076    /** Azimuthal angle in the x-y plane. */
077    private final double azimuth;
078
079    /** Polar angle. */
080    private final double polar;
081
082    /** Corresponding 3D normalized vector. */
083    private final Vector3D.Unit vector;
084
085    /** Build a point from its internal components.
086     * @param azimuth azimuthal angle in the x-y plane
087     * @param polar polar angle
088     * @param vector corresponding vector; if null, the vector is computed
089     */
090    private Point2S(final double azimuth, final double polar, final Vector3D.Unit vector) {
091        this.azimuth = SphericalCoordinates.normalizeAzimuth(azimuth);
092        this.polar = SphericalCoordinates.normalizePolar(polar);
093        this.vector = (vector != null) ?
094                vector :
095                computeVector(azimuth, polar);
096    }
097
098    /** Get the azimuth angle in the x-y plane in the range {@code [0, 2pi)}.
099     * @return azimuth angle in the x-y plane in the range {@code [0, 2pi)}.
100     * @see Point2S#of(double, double)
101     */
102    public double getAzimuth() {
103        return azimuth;
104    }
105
106    /** Get the polar angle in the range {@code [0, pi)}.
107     * @return polar angle in the range {@code [0, pi)}.
108     * @see Point2S#of(double, double)
109     */
110    public double getPolar() {
111        return polar;
112    }
113
114    /** Get the corresponding normalized vector in 3D Euclidean space.
115     * This value will be null if the spherical coordinates of the point
116     * are infinite or NaN.
117     * @return normalized vector
118     */
119    public Vector3D.Unit getVector() {
120        return vector;
121    }
122
123    /** {@inheritDoc} */
124    @Override
125    public int getDimension() {
126        return 2;
127    }
128
129    /** {@inheritDoc} */
130    @Override
131    public boolean isNaN() {
132        return Double.isNaN(azimuth) || Double.isNaN(polar);
133    }
134
135    /** {@inheritDoc} */
136    @Override
137    public boolean isInfinite() {
138        return !isNaN() && (Double.isInfinite(azimuth) || Double.isInfinite(polar));
139    }
140
141    /** {@inheritDoc} */
142    @Override
143    public boolean isFinite() {
144        return Double.isFinite(azimuth) && Double.isFinite(polar);
145    }
146
147    /** Get the point exactly opposite this point on the sphere. The returned
148     * point is {@code pi} distance away from the current instance.
149     * @return the point exactly opposite this point on the sphere
150     */
151    public Point2S antipodal() {
152        return from(vector.negate());
153    }
154
155    /** {@inheritDoc} */
156    @Override
157    public double distance(final Point2S point) {
158        return distance(this, point);
159    }
160
161    /** Spherically interpolate a point along the shortest arc between this point and
162     * the given point. The parameter {@code t} controls the interpolation and is expected
163     * to be in the range {@code [0, 1]}, with {@code 0} returning a point equivalent to the
164     * current instance {@code 1} returning a point equivalent to the given instance. If the
165     * points are antipodal, then an arbitrary arc is chosen from the infinite number available.
166     * @param other other point to interpolate with
167     * @param t interpolation parameter
168     * @return spherically interpolated point
169     * @see QuaternionRotation#slerp(QuaternionRotation)
170     * @see QuaternionRotation#createVectorRotation(Vector3D, Vector3D)
171     */
172    public Point2S slerp(final Point2S other, final double t) {
173        final QuaternionRotation start = QuaternionRotation.identity();
174        final QuaternionRotation end = QuaternionRotation.createVectorRotation(getVector(), other.getVector());
175
176        final QuaternionRotation quat = start.slerp(end).apply(t);
177
178        return Point2S.from(quat.apply(getVector()));
179    }
180
181    /** Return true if this point should be considered equivalent to the argument using the
182     * given precision context. This will be true if the distance between the points is
183     * equivalent to zero as evaluated by the precision context.
184     * @param point point to compare with
185     * @param precision precision context used to perform floating point comparisons
186     * @return true if this point should be considered equivalent to the argument using the
187     *      given precision context
188     */
189    public boolean eq(final Point2S point, final Precision.DoubleEquivalence precision) {
190        return precision.eqZero(distance(point));
191    }
192
193    /** Get a hashCode for the point.
194     * .
195     * <p>All NaN values have the same hash code.</p>
196     *
197     * @return a hash code value for this object
198     */
199    @Override
200    public int hashCode() {
201        if (isNaN()) {
202            return 542;
203        }
204        return 134 * (37 * Double.hashCode(azimuth) +  Double.hashCode(polar));
205    }
206
207    /** Test for the equality of two points.
208     *
209     * <p>If all spherical coordinates of two points are exactly the same, and none are
210     * <code>Double.NaN</code>, the two points are considered to be equal. Note
211     * that the comparison is made using the azimuth and polar coordinates only; the
212     * corresponding 3D vectors are not compared. This is significant at the poles,
213     * where an infinite number of points share the same underlying 3D vector but may
214     * have different spherical coordinates. For example, the points {@code (0, 0)}
215     * and {@code (1, 0)} (both located at a pole but with different azimuths) will
216     * <em>not</em> be considered equal by this method, even though they share the
217     * exact same underlying 3D vector.</p>
218     *
219     * <p>
220     * <code>NaN</code> coordinates are considered to affect the point globally
221     * and be equals to each other - i.e, if either (or all) coordinates of the
222     * point are equal to <code>Double.NaN</code>, the point is equal to
223     * {@link #NaN}.
224     * </p>
225     *
226     * @param other Object to test for equality to this
227     * @return true if two points on the 2-sphere objects are exactly equal, false if
228     *         object is null, not an instance of Point2S, or
229     *         not equal to this Point2S instance
230     */
231    @Override
232    public boolean equals(final Object other) {
233        if (this == other) {
234            return true;
235        }
236        if (!(other instanceof Point2S)) {
237            return false;
238        }
239
240        final Point2S rhs = (Point2S) other;
241        if (rhs.isNaN()) {
242            return this.isNaN();
243        }
244
245        return Double.compare(azimuth, rhs.azimuth) == 0 &&
246                Double.compare(polar, rhs.polar) == 0;
247    }
248
249    /** {@inheritDoc} */
250    @Override
251    public String toString() {
252        return SimpleTupleFormat.getDefault().format(getAzimuth(), getPolar());
253    }
254
255    /** Build a vector from its spherical coordinates.
256     * @param azimuth azimuthal angle in the x-y plane
257     * @param polar polar angle
258     * @return point instance with the given coordinates
259     * @see #getAzimuth()
260     * @see #getPolar()
261     */
262    public static Point2S of(final double azimuth, final double polar) {
263        return new Point2S(azimuth, polar, null);
264    }
265
266    /** Build a point from its underlying 3D vector.
267     * @param vector 3D vector
268     * @return point instance with the coordinates determined by the given 3D vector
269     * @exception IllegalStateException if vector norm is zero
270     */
271    public static Point2S from(final Vector3D vector) {
272        final SphericalCoordinates coords = SphericalCoordinates.fromCartesian(vector);
273
274        return new Point2S(coords.getAzimuth(), coords.getPolar(), vector.normalize());
275    }
276
277    /** Parses the given string and returns a new point instance. The expected string
278     * format is the same as that returned by {@link #toString()}.
279     * @param str the string to parse
280     * @return point instance represented by the string
281     * @throws IllegalArgumentException if the given string has an invalid format
282     */
283    public static Point2S parse(final String str) {
284        return SimpleTupleFormat.getDefault().parse(str, Point2S::of);
285    }
286
287    /** Compute the distance (angular separation) between two points.
288     * @param p1 first vector
289     * @param p2 second vector
290     * @return the angular separation between p1 and p2
291     */
292    public static double distance(final Point2S p1, final Point2S p2) {
293        return p1.vector.angle(p2.vector);
294    }
295
296    /** Compute the 3D Euclidean vector associated with the given spherical coordinates.
297     * Null is returned if the coordinates are infinite or NaN.
298     * @param azimuth azimuth value
299     * @param polar polar value
300     * @return the 3D Euclidean vector associated with the given spherical coordinates
301     *      or null if either of the arguments are infinite or NaN.
302     */
303    private static Vector3D.Unit computeVector(final double azimuth, final double polar) {
304        if (Double.isFinite(azimuth) && Double.isFinite(polar)) {
305            return SphericalCoordinates.toCartesian(1, azimuth, polar).normalize();
306        }
307        return null;
308    }
309}