FieldOfView.java

  1. /* Copyright 2002-2019 CS Systèmes d'Information
  2.  * Licensed to CS Systèmes d'Information (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS 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.orekit.propagation.events;

  18. import java.io.Serializable;
  19. import java.util.ArrayList;
  20. import java.util.List;

  21. import org.hipparchus.exception.LocalizedCoreFormats;
  22. import org.hipparchus.geometry.enclosing.EnclosingBall;
  23. import org.hipparchus.geometry.euclidean.threed.Line;
  24. import org.hipparchus.geometry.euclidean.threed.Rotation;
  25. import org.hipparchus.geometry.euclidean.threed.RotationConvention;
  26. import org.hipparchus.geometry.euclidean.threed.Vector3D;
  27. import org.hipparchus.geometry.partitioning.Region;
  28. import org.hipparchus.geometry.partitioning.RegionFactory;
  29. import org.hipparchus.geometry.spherical.twod.Edge;
  30. import org.hipparchus.geometry.spherical.twod.S2Point;
  31. import org.hipparchus.geometry.spherical.twod.Sphere2D;
  32. import org.hipparchus.geometry.spherical.twod.SphericalPolygonsSet;
  33. import org.hipparchus.geometry.spherical.twod.Vertex;
  34. import org.hipparchus.util.FastMath;
  35. import org.hipparchus.util.MathUtils;
  36. import org.orekit.bodies.GeodeticPoint;
  37. import org.orekit.bodies.OneAxisEllipsoid;
  38. import org.orekit.errors.OrekitException;
  39. import org.orekit.errors.OrekitMessages;
  40. import org.orekit.frames.Frame;
  41. import org.orekit.frames.Transform;
  42. import org.orekit.utils.SphericalPolygonsSetTransferObject;

  43. /** Class representing a spacecraft sensor Field Of View.
  44.  * <p>Fields Of View are zones defined on the unit sphere centered on the
  45.  * spacecraft. They can have any shape, they can be split in several
  46.  * non-connected patches and can have holes.</p>
  47.  * @see org.orekit.propagation.events.FootprintOverlapDetector
  48.  * @author Luc Maisonobe
  49.  * @since 7.1
  50.  */
  51. public class FieldOfView implements Serializable {

  52.     /** Serializable UID. */
  53.     private static final long serialVersionUID = 20150113L;

  54.     /** Spherical zone. */
  55.     private final transient SphericalPolygonsSet zone;

  56.     /** Margin to apply to the zone. */
  57.     private final double margin;

  58.     /** Spherical cap surrounding the zone. */
  59.     private final transient EnclosingBall<Sphere2D, S2Point> cap;

  60.     /** Build a new instance.
  61.      * @param zone interior of the Field Of View, in spacecraft frame
  62.      * @param margin angular margin to apply to the zone (if positive,
  63.      * the Field Of View will consider points slightly outside of the
  64.      * zone are still visible)
  65.      */
  66.     public FieldOfView(final SphericalPolygonsSet zone, final double margin) {
  67.         this.zone   = zone;
  68.         this.margin = margin;
  69.         this.cap    = zone.getEnclosingCap();
  70.     }

  71.     /** Build a Field Of View with dihedral shape (i.e. rectangular shape).
  72.      * @param center Direction of the FOV center, in spacecraft frame
  73.      * @param axis1 FOV dihedral axis 1, in spacecraft frame
  74.      * @param halfAperture1 FOV dihedral half aperture angle 1,
  75.      * must be less than π/2, i.e. full dihedra must be smaller then
  76.      * an hemisphere
  77.      * @param axis2 FOV dihedral axis 2, in spacecraft frame
  78.      * @param halfAperture2 FOV dihedral half aperture angle 2,
  79.      * must be less than π/2, i.e. full dihedra must be smaller then
  80.      * an hemisphere
  81.      * @param margin angular margin to apply to the zone (if positive,
  82.      * the Field Of View will consider points slightly outside of the
  83.      * zone are still visible)
  84.      */
  85.     public FieldOfView(final Vector3D center,
  86.                        final Vector3D axis1, final double halfAperture1,
  87.                        final Vector3D axis2, final double halfAperture2,
  88.                        final double margin) {

  89.         // build zone
  90.         final RegionFactory<Sphere2D> factory = new RegionFactory<Sphere2D>();
  91.         final double tolerance = FastMath.max(FastMath.ulp(2.0 * FastMath.PI),
  92.                                               1.0e-12 * FastMath.max(halfAperture1, halfAperture2));
  93.         final Region<Sphere2D> dihedra1 = buildDihedra(factory, tolerance, center, axis1, halfAperture1);
  94.         final Region<Sphere2D> dihedra2 = buildDihedra(factory, tolerance, center, axis2, halfAperture2);
  95.         this.zone = (SphericalPolygonsSet) factory.intersection(dihedra1, dihedra2);

  96.         this.margin = margin;
  97.         this.cap    = zone.getEnclosingCap();

  98.     }

  99.     /** Build Field Of View with a regular polygon shape.
  100.      * @param center center of the polygon (the center is in the inside part)
  101.      * @param meridian point defining the reference meridian for middle of first edge
  102.      * @param insideRadius distance of the edges middle points to the center
  103.      * (the polygon vertices will therefore be farther away from the center)
  104.      * @param n number of sides of the polygon
  105.      * @param margin angular margin to apply to the zone (if positive,
  106.      * the Field Of View will consider points slightly outside of the
  107.      * zone are still visible)
  108.      */
  109.     public FieldOfView(final Vector3D center, final Vector3D meridian,
  110.                        final double insideRadius, final int n, final double margin) {

  111.         // convert the representation based on middle edge points
  112.         // to Hipparchus convention based on vertices
  113.         final Rotation r                = new Rotation(center, MathUtils.TWO_PI / n,
  114.                                                        RotationConvention.VECTOR_OPERATOR);
  115.         final Vector3D orthogonal       = Vector3D.crossProduct(Vector3D.crossProduct(center, meridian), center);
  116.         final Vector3D firstEdgeNormal  = new Vector3D( FastMath.sin(insideRadius), center.normalize(),
  117.                                                        -FastMath.cos(insideRadius), orthogonal.normalize());
  118.         final Vector3D secondEdgeNormal = r.applyTo(firstEdgeNormal);
  119.         final Vector3D vertex           = Vector3D.crossProduct(firstEdgeNormal, secondEdgeNormal);
  120.         final double outsideRadius      = Vector3D.angle(center, vertex);
  121.         this.zone = new SphericalPolygonsSet(center, vertex, outsideRadius, n, 1.0e-12 * insideRadius);

  122.         this.margin = margin;

  123.         final S2Point[] support = new S2Point[n];
  124.         support[0] = new S2Point(vertex);
  125.         for (int i = 1; i < n; ++i) {
  126.             support[i] = new S2Point(r.applyTo(support[i - 1].getVector()));
  127.         }
  128.         this.cap = new EnclosingBall<Sphere2D, S2Point>(new S2Point(center), outsideRadius, support);

  129.     }

  130.     /** Build a dihedra.
  131.      * @param factory factory for regions
  132.      * @param tolerance tolerance below which points are considered equal
  133.      * @param center Direction of the FOV center, in spacecraft frame
  134.      * @param axis FOV dihedral axis, in spacecraft frame
  135.      * @param halfAperture FOV dihedral half aperture angle,
  136.      * must be less than π/2, i.e. full dihedra must be smaller then
  137.      * an hemisphere
  138.      * @return dihedra
  139.      */
  140.     private Region<Sphere2D> buildDihedra(final RegionFactory<Sphere2D> factory,
  141.                                           final double tolerance, final Vector3D center,
  142.                                           final Vector3D axis, final double halfAperture) {
  143.         if (halfAperture > 0.5 * FastMath.PI) {
  144.             throw new OrekitException(LocalizedCoreFormats.OUT_OF_RANGE_SIMPLE,
  145.                                       halfAperture, 0.0, 0.5 * FastMath.PI);
  146.         }

  147.         final Rotation r = new Rotation(axis, halfAperture, RotationConvention.VECTOR_OPERATOR);
  148.         final Vector3D normalCenterPlane = Vector3D.crossProduct(axis, center);
  149.         final Vector3D normalSidePlus    = r.applyInverseTo(normalCenterPlane);
  150.         final Vector3D normalSideMinus   = r.applyTo(normalCenterPlane.negate());

  151.         return factory.intersection(new SphericalPolygonsSet(normalSidePlus,  tolerance),
  152.                                     new SphericalPolygonsSet(normalSideMinus, tolerance));

  153.     }

  154.     /** Get the interior zone.
  155.      * @return the interior zone
  156.      */
  157.     public SphericalPolygonsSet getZone() {
  158.         return zone;
  159.     }

  160.     /** Get the angular margin to apply (radians).
  161.      * @return the angular margin to apply (radians)
  162.      */
  163.     public double getMargin() {
  164.         return margin;
  165.     }

  166.     /** Get the angular offset of target point with respect to the Field Of View Boundary.
  167.      * <p>
  168.      * The offset is roughly an angle with respect to the closest boundary point,
  169.      * corrected by the margin and using some approximation far from the Field Of View.
  170.      * It is positive if the target is outside of the Field Of view, negative inside,
  171.      * and zero if the point is exactly on the boundary (always taking the margin
  172.      * into account).
  173.      * </p>
  174.      * <p>
  175.      * As Field Of View can have complex shapes that may require long computation,
  176.      * when the target point can be proven to be outside of the Field Of View, a
  177.      * faster but approximate computation is done, that underestimate the offset.
  178.      * This approximation is only performed about 0.01 radians outside of the zone
  179.      * and is designed to still return a positive value if the full accurate computation
  180.      * would return a positive value. When target point is close to the zone (and
  181.      * furthermore when it is inside the zone), the full accurate computation is
  182.      * performed. This setup allows this offset to be used as a reliable way to
  183.      * detect Field Of View boundary crossings, which correspond to sign changes of
  184.      * the offset.
  185.      * </p>
  186.      * @param lineOfSight line of sight from the center of the Field Of View support
  187.      * unit sphere to the target in Field Of View canonical frame
  188.      * @return an angular offset negative if the target is visible within the Field Of
  189.      * View and positive if it is outside of the Field Of View, including the margin
  190.      * (note that this cannot take into account interposing bodies)
  191.      */
  192.     public double offsetFromBoundary(final Vector3D lineOfSight) {

  193.         final S2Point los = new S2Point(lineOfSight);

  194.         // for faster computation, we start using only the surrounding cap, to filter out
  195.         // far away points (which correspond to most of the points if the Field Of View is small)
  196.         final double crudeDistance = cap.getCenter().distance(los) - cap.getRadius();
  197.         if (crudeDistance - margin > FastMath.max(FastMath.abs(margin), 0.01)) {
  198.             // we know we are strictly outside of the zone,
  199.             // use the crude distance to compute the (positive) return value
  200.             return crudeDistance - margin;
  201.         }

  202.         // we are close, we need to compute carefully the exact offset;
  203.         // we project the point to the closest zone boundary
  204.         return zone.projectToBoundary(los).getOffset() - margin;

  205.     }

  206.     /** Get the footprint of the field Of View on ground.
  207.      * <p>
  208.      * This method assumes the Field Of View is centered on some carrier,
  209.      * which will typically be a spacecraft or a ground station antenna.
  210.      * The points in the footprint boundary loops are all at altitude zero
  211.      * with respect to the ellipsoid, they correspond either to projection
  212.      * on ground of the edges of the Field Of View, or to points on the body
  213.      * limb if the Field Of View goes past horizon. The points on the limb
  214.      * see the carrier origin at zero elevation. If the Field Of View is so
  215.      * large it contains entirely the body, all points will correspond to
  216.      * points at limb. If the Field Of View looks away from body, the
  217.      * boundary loops will be an empty list. The points within footprint
  218.      * the loops are sorted in trigonometric order as seen from the carrier.
  219.      * This implies that someone traveling on ground from one point to the
  220.      * next one will have the points visible from the carrier on his left
  221.      * hand side, and the points not visible from the carrier on his right
  222.      * hand side.
  223.      * </p>
  224.      * <p>
  225.      * The truncation of Field Of View at limb can induce strange results
  226.      * for complex Fields Of View. If for example a Field Of View is a
  227.      * ring with a hole and part of the ring goes past horizon, then instead
  228.      * of having a single loop with a C-shaped boundary, the method will
  229.      * still return two loops truncated at the limb, one clockwise and one
  230.      * counterclockwise, hence "closing" the C-shape twice. This behavior
  231.      * is considered acceptable.
  232.      * </p>
  233.      * <p>
  234.      * If the carrier is a spacecraft, then the {@code fovToBody} transform
  235.      * can be computed from a {@link org.orekit.propagation.SpacecraftState}
  236.      * as follows:
  237.      * </p>
  238.      * <pre>
  239.      * Transform inertToBody = state.getFrame().getTransformTo(body.getBodyFrame(), state.getDate());
  240.      * Transform fovToBody   = new Transform(state.getDate(),
  241.      *                                       state.toTransform().getInverse(),
  242.      *                                       inertToBody);
  243.      * </pre>
  244.      * <p>
  245.      * If the carrier is a ground station, located using a topocentric frame
  246.      * and managing its pointing direction using a transform between the
  247.      * dish frame and the topocentric frame, then the {@code fovToBody} transform
  248.      * can be computed as follows:
  249.      * </p>
  250.      * <pre>
  251.      * Transform topoToBody = topocentricFrame.getTransformTo(body.getBodyFrame(), date);
  252.      * Transform topoToDish = ...
  253.      * Transform fovToBody  = new Transform(date,
  254.      *                                      topoToDish.getInverse(),
  255.      *                                      topoToBody);
  256.      * </pre>
  257.      * <p>
  258.      * Only the raw zone is used, the angular margin is ignored here.
  259.      * </p>
  260.      * @param fovToBody transform between the frame in which the Field Of View
  261.      * is defined and body frame.
  262.      * @param body body surface the Field Of View will be projected on
  263.      * @param angularStep step used for boundary loops sampling (radians)
  264.      * @return list footprint boundary loops (there may be several independent
  265.      * loops if the Field Of View shape is complex)
  266.      */
  267.     List<List<GeodeticPoint>> getFootprint(final Transform fovToBody, final OneAxisEllipsoid body,
  268.                                            final double angularStep) {

  269.         final Frame     bodyFrame = body.getBodyFrame();
  270.         final Vector3D  position  = fovToBody.transformPosition(Vector3D.ZERO);
  271.         final double    r         = position.getNorm();
  272.         if (body.isInside(position)) {
  273.             throw new OrekitException(OrekitMessages.POINT_INSIDE_ELLIPSOID);
  274.         }

  275.         final List<List<GeodeticPoint>> footprint = new ArrayList<List<GeodeticPoint>>();

  276.         final List<Vertex> boundary = zone.getBoundaryLoops();
  277.         for (final Vertex loopStart : boundary) {
  278.             int count = 0;
  279.             final List<GeodeticPoint> loop  = new ArrayList<GeodeticPoint>();
  280.             boolean intersectionsFound      = false;
  281.             for (Edge edge = loopStart.getOutgoing();
  282.                  count == 0 || edge.getStart() != loopStart;
  283.                  edge = edge.getEnd().getOutgoing()) {
  284.                 ++count;
  285.                 final int    n     = (int) FastMath.ceil(edge.getLength() / angularStep);
  286.                 final double delta =  edge.getLength() / n;
  287.                 for (int i = 0; i < n; ++i) {
  288.                     final Vector3D awaySC      = new Vector3D(r, edge.getPointAt(i * delta));
  289.                     final Vector3D awayBody    = fovToBody.transformPosition(awaySC);
  290.                     final Line     lineOfSight = new Line(position, awayBody, 1.0e-3);
  291.                     GeodeticPoint  gp          = body.getIntersectionPoint(lineOfSight, position,
  292.                                                                            bodyFrame, null);
  293.                     if (gp != null &&
  294.                         Vector3D.dotProduct(awayBody.subtract(position),
  295.                                             body.transform(gp).subtract(position)) < 0) {
  296.                         // the intersection is in fact on the half-line pointing
  297.                         // towards the back side, it is a spurious intersection
  298.                         gp = null;
  299.                     }

  300.                     if (gp != null) {
  301.                         // the line of sight does intersect the body
  302.                         intersectionsFound = true;
  303.                     } else {
  304.                         // the line of sight does not intersect body
  305.                         // we use a point on the limb
  306.                         gp = body.transform(body.pointOnLimb(position, awayBody), bodyFrame, null);
  307.                     }

  308.                     // add the point in front of the list
  309.                     // (to ensure the loop will be in trigonometric orientation)
  310.                     loop.add(0, gp);

  311.                 }
  312.             }

  313.             if (intersectionsFound) {
  314.                 // at least some of the points did intersect the body,
  315.                 // this loop contributes to the footprint
  316.                 footprint.add(loop);
  317.             }

  318.         }

  319.         if (footprint.isEmpty()) {
  320.             // none of the Field Of View loops cross the body
  321.             // either the body is outside of Field Of View, or it is fully contained
  322.             // we check the center
  323.             final Vector3D bodyCenter = fovToBody.getInverse().transformPosition(Vector3D.ZERO);
  324.             if (zone.checkPoint(new S2Point(bodyCenter)) != Region.Location.OUTSIDE) {
  325.                 // the body is fully contained in the Field Of View
  326.                 // we use the full limb as the footprint
  327.                 final Vector3D x        = bodyCenter.orthogonal();
  328.                 final Vector3D y        = Vector3D.crossProduct(bodyCenter, x).normalize();
  329.                 final double   sinEta   = body.getEquatorialRadius() / r;
  330.                 final double   sinEta2  = sinEta * sinEta;
  331.                 final double   cosAlpha = (FastMath.cos(angularStep) + sinEta2 - 1) / sinEta2;
  332.                 final int      n        = (int) FastMath.ceil(MathUtils.TWO_PI / FastMath.acos(cosAlpha));
  333.                 final double   delta    = MathUtils.TWO_PI / n;
  334.                 final List<GeodeticPoint> loop = new ArrayList<GeodeticPoint>(n);
  335.                 for (int i = 0; i < n; ++i) {
  336.                     final Vector3D outside = new Vector3D(r * FastMath.cos(i * delta), x,
  337.                                                           r * FastMath.sin(i * delta), y);
  338.                     loop.add(body.transform(body.pointOnLimb(position, outside), bodyFrame, null));
  339.                 }
  340.                 footprint.add(loop);
  341.             }
  342.         }

  343.         return footprint;

  344.     }

  345.     /** Replace the instance with a data transfer object for serialization.
  346.      * @return data transfer object that will be serialized
  347.      */
  348.     private Object writeReplace() {
  349.         return new DTO(this);
  350.     }

  351.     /** Internal class used only for serialization. */
  352.     private static class DTO implements Serializable {

  353.         /** Serializable UID. */
  354.         private static final long serialVersionUID = 20150113L;

  355.         /** Proxy for interior zone. */
  356.         private final SphericalPolygonsSetTransferObject zone;

  357.         /** Angular margin. */
  358.         private final double margin;

  359.         /** Simple constructor.
  360.          * @param fov instance to serialize
  361.          */
  362.         private DTO(final FieldOfView fov) {
  363.             this.zone   = new SphericalPolygonsSetTransferObject(fov.zone);
  364.             this.margin = fov.margin;
  365.         }

  366.         /** Replace the deserialized data transfer object with a {@link FieldOfView}.
  367.          * @return replacement {@link FieldOfView}
  368.          */
  369.         private Object readResolve() {
  370.             return new FieldOfView(zone.rebuildZone(), margin);
  371.         }

  372.     }

  373. }