001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import java.awt.Rectangle;
005import java.awt.geom.Area;
006import java.awt.geom.Line2D;
007import java.awt.geom.Path2D;
008import java.math.BigDecimal;
009import java.math.MathContext;
010import java.util.ArrayList;
011import java.util.Collections;
012import java.util.Comparator;
013import java.util.EnumSet;
014import java.util.HashSet;
015import java.util.LinkedHashSet;
016import java.util.List;
017import java.util.Set;
018
019import org.openstreetmap.josm.Main;
020import org.openstreetmap.josm.command.AddCommand;
021import org.openstreetmap.josm.command.ChangeCommand;
022import org.openstreetmap.josm.command.Command;
023import org.openstreetmap.josm.data.coor.EastNorth;
024import org.openstreetmap.josm.data.coor.LatLon;
025import org.openstreetmap.josm.data.osm.BBox;
026import org.openstreetmap.josm.data.osm.MultipolygonBuilder;
027import org.openstreetmap.josm.data.osm.Node;
028import org.openstreetmap.josm.data.osm.NodePositionComparator;
029import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
030import org.openstreetmap.josm.data.osm.Relation;
031import org.openstreetmap.josm.data.osm.RelationMember;
032import org.openstreetmap.josm.data.osm.Way;
033
034/**
035 * Some tools for geometry related tasks.
036 *
037 * @author viesturs
038 */
039public final class Geometry {
040
041    private Geometry() {
042        // Hide default constructor for utils classes
043    }
044
045    public enum PolygonIntersection {
046        FIRST_INSIDE_SECOND,
047        SECOND_INSIDE_FIRST,
048        OUTSIDE,
049        CROSSING
050    }
051
052    /**
053     * Will find all intersection and add nodes there for list of given ways.
054     * Handles self-intersections too.
055     * And makes commands to add the intersection points to ways.
056     *
057     * Prerequisite: no two nodes have the same coordinates.
058     *
059     * @param ways  a list of ways to test
060     * @param test  if false, do not build list of Commands, just return nodes
061     * @param cmds  list of commands, typically empty when handed to this method.
062     *              Will be filled with commands that add intersection nodes to
063     *              the ways.
064     * @return list of new nodes
065     */
066    public static Set<Node> addIntersections(List<Way> ways, boolean test, List<Command> cmds) {
067
068        int n = ways.size();
069        @SuppressWarnings("unchecked")
070        List<Node>[] newNodes = new ArrayList[n];
071        BBox[] wayBounds = new BBox[n];
072        boolean[] changedWays = new boolean[n];
073
074        Set<Node> intersectionNodes = new LinkedHashSet<>();
075
076        //copy node arrays for local usage.
077        for (int pos = 0; pos < n; pos++) {
078            newNodes[pos] = new ArrayList<>(ways.get(pos).getNodes());
079            wayBounds[pos] = getNodesBounds(newNodes[pos]);
080            changedWays[pos] = false;
081        }
082
083        //iterate over all way pairs and introduce the intersections
084        Comparator<Node> coordsComparator = new NodePositionComparator();
085        for (int seg1Way = 0; seg1Way < n; seg1Way++) {
086            for (int seg2Way = seg1Way; seg2Way < n; seg2Way++) {
087
088                //do not waste time on bounds that do not intersect
089                if (!wayBounds[seg1Way].intersects(wayBounds[seg2Way])) {
090                    continue;
091                }
092
093                List<Node> way1Nodes = newNodes[seg1Way];
094                List<Node> way2Nodes = newNodes[seg2Way];
095
096                //iterate over primary segmemt
097                for (int seg1Pos = 0; seg1Pos + 1 < way1Nodes.size(); seg1Pos++) {
098
099                    //iterate over secondary segment
100                    int seg2Start = seg1Way != seg2Way ? 0 : seg1Pos + 2; //skip the adjacent segment
101
102                    for (int seg2Pos = seg2Start; seg2Pos + 1 < way2Nodes.size(); seg2Pos++) {
103
104                        //need to get them again every time, because other segments may be changed
105                        Node seg1Node1 = way1Nodes.get(seg1Pos);
106                        Node seg1Node2 = way1Nodes.get(seg1Pos + 1);
107                        Node seg2Node1 = way2Nodes.get(seg2Pos);
108                        Node seg2Node2 = way2Nodes.get(seg2Pos + 1);
109
110                        int commonCount = 0;
111                        //test if we have common nodes to add.
112                        if (seg1Node1 == seg2Node1 || seg1Node1 == seg2Node2) {
113                            commonCount++;
114
115                            if (seg1Way == seg2Way &&
116                                    seg1Pos == 0 &&
117                                    seg2Pos == way2Nodes.size() -2) {
118                                //do not add - this is first and last segment of the same way.
119                            } else {
120                                intersectionNodes.add(seg1Node1);
121                            }
122                        }
123
124                        if (seg1Node2 == seg2Node1 || seg1Node2 == seg2Node2) {
125                            commonCount++;
126
127                            intersectionNodes.add(seg1Node2);
128                        }
129
130                        //no common nodes - find intersection
131                        if (commonCount == 0) {
132                            EastNorth intersection = getSegmentSegmentIntersection(
133                                    seg1Node1.getEastNorth(), seg1Node2.getEastNorth(),
134                                    seg2Node1.getEastNorth(), seg2Node2.getEastNorth());
135
136                            if (intersection != null) {
137                                if (test) {
138                                    intersectionNodes.add(seg2Node1);
139                                    return intersectionNodes;
140                                }
141
142                                Node newNode = new Node(Main.getProjection().eastNorth2latlon(intersection));
143                                Node intNode = newNode;
144                                boolean insertInSeg1 = false;
145                                boolean insertInSeg2 = false;
146                                //find if the intersection point is at end point of one of the segments, if so use that point
147
148                                //segment 1
149                                if (coordsComparator.compare(newNode, seg1Node1) == 0) {
150                                    intNode = seg1Node1;
151                                } else if (coordsComparator.compare(newNode, seg1Node2) == 0) {
152                                    intNode = seg1Node2;
153                                } else {
154                                    insertInSeg1 = true;
155                                }
156
157                                //segment 2
158                                if (coordsComparator.compare(newNode, seg2Node1) == 0) {
159                                    intNode = seg2Node1;
160                                } else if (coordsComparator.compare(newNode, seg2Node2) == 0) {
161                                    intNode = seg2Node2;
162                                } else {
163                                    insertInSeg2 = true;
164                                }
165
166                                if (insertInSeg1) {
167                                    way1Nodes.add(seg1Pos +1, intNode);
168                                    changedWays[seg1Way] = true;
169
170                                    //fix seg2 position, as indexes have changed, seg2Pos is always bigger than seg1Pos on the same segment.
171                                    if (seg2Way == seg1Way) {
172                                        seg2Pos++;
173                                    }
174                                }
175
176                                if (insertInSeg2) {
177                                    way2Nodes.add(seg2Pos +1, intNode);
178                                    changedWays[seg2Way] = true;
179
180                                    //Do not need to compare again to already split segment
181                                    seg2Pos++;
182                                }
183
184                                intersectionNodes.add(intNode);
185
186                                if (intNode == newNode) {
187                                    cmds.add(new AddCommand(intNode));
188                                }
189                            }
190                        } else if (test && !intersectionNodes.isEmpty())
191                            return intersectionNodes;
192                    }
193                }
194            }
195        }
196
197
198        for (int pos = 0; pos < ways.size(); pos++) {
199            if (!changedWays[pos]) {
200                continue;
201            }
202
203            Way way = ways.get(pos);
204            Way newWay = new Way(way);
205            newWay.setNodes(newNodes[pos]);
206
207            cmds.add(new ChangeCommand(way, newWay));
208        }
209
210        return intersectionNodes;
211    }
212
213    private static BBox getNodesBounds(List<Node> nodes) {
214
215        BBox bounds = new BBox(nodes.get(0));
216        for (Node n: nodes) {
217            bounds.add(n.getCoor());
218        }
219        return bounds;
220    }
221
222    /**
223     * Tests if given point is to the right side of path consisting of 3 points.
224     *
225     * (Imagine the path is continued beyond the endpoints, so you get two rays
226     * starting from lineP2 and going through lineP1 and lineP3 respectively
227     * which divide the plane into two parts. The test returns true, if testPoint
228     * lies in the part that is to the right when traveling in the direction
229     * lineP1, lineP2, lineP3.)
230     *
231     * @param lineP1 first point in path
232     * @param lineP2 second point in path
233     * @param lineP3 third point in path
234     * @param testPoint point to test
235     * @return true if to the right side, false otherwise
236     */
237    public static boolean isToTheRightSideOfLine(Node lineP1, Node lineP2, Node lineP3, Node testPoint) {
238        boolean pathBendToRight = angleIsClockwise(lineP1, lineP2, lineP3);
239        boolean rightOfSeg1 = angleIsClockwise(lineP1, lineP2, testPoint);
240        boolean rightOfSeg2 = angleIsClockwise(lineP2, lineP3, testPoint);
241
242        if (pathBendToRight)
243            return rightOfSeg1 && rightOfSeg2;
244        else
245            return !(!rightOfSeg1 && !rightOfSeg2);
246    }
247
248    /**
249     * This method tests if secondNode is clockwise to first node.
250     * @param commonNode starting point for both vectors
251     * @param firstNode first vector end node
252     * @param secondNode second vector end node
253     * @return true if first vector is clockwise before second vector.
254     */
255    public static boolean angleIsClockwise(Node commonNode, Node firstNode, Node secondNode) {
256        return angleIsClockwise(commonNode.getEastNorth(), firstNode.getEastNorth(), secondNode.getEastNorth());
257    }
258
259    /**
260     * Finds the intersection of two line segments
261     * @return EastNorth null if no intersection was found, the EastNorth coordinates of the intersection otherwise
262     */
263    public static EastNorth getSegmentSegmentIntersection(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) {
264
265        CheckParameterUtil.ensureValidCoordinates(p1, "p1");
266        CheckParameterUtil.ensureValidCoordinates(p2, "p2");
267        CheckParameterUtil.ensureValidCoordinates(p3, "p3");
268        CheckParameterUtil.ensureValidCoordinates(p4, "p4");
269
270        double x1 = p1.getX();
271        double y1 = p1.getY();
272        double x2 = p2.getX();
273        double y2 = p2.getY();
274        double x3 = p3.getX();
275        double y3 = p3.getY();
276        double x4 = p4.getX();
277        double y4 = p4.getY();
278
279        //TODO: do this locally.
280        //TODO: remove this check after careful testing
281        if (!Line2D.linesIntersect(x1, y1, x2, y2, x3, y3, x4, y4)) return null;
282
283        // solve line-line intersection in parametric form:
284        // (x1,y1) + (x2-x1,y2-y1)* u  = (x3,y3) + (x4-x3,y4-y3)* v
285        // (x2-x1,y2-y1)*u - (x4-x3,y4-y3)*v = (x3-x1,y3-y1)
286        // if 0<= u,v <=1, intersection exists at ( x1+ (x2-x1)*u, y1 + (y2-y1)*u )
287
288        double a1 = x2 - x1;
289        double b1 = x3 - x4;
290        double c1 = x3 - x1;
291
292        double a2 = y2 - y1;
293        double b2 = y3 - y4;
294        double c2 = y3 - y1;
295
296        // Solve the equations
297        double det = a1*b2 - a2*b1;
298
299        double uu = b2*c1 - b1*c2;
300        double vv = a1*c2 - a2*c1;
301        double mag = Math.abs(uu)+Math.abs(vv);
302
303        if (Math.abs(det) > 1e-12 * mag) {
304            double u = uu/det, v = vv/det;
305            if (u > -1e-8 && u < 1+1e-8 && v > -1e-8 && v < 1+1e-8) {
306                if (u < 0) u = 0;
307                if (u > 1) u = 1.0;
308                return new EastNorth(x1+a1*u, y1+a2*u);
309            } else {
310                return null;
311            }
312        } else {
313            // parallel lines
314            return null;
315        }
316    }
317
318    /**
319     * Finds the intersection of two lines of infinite length.
320     *
321     * @param p1 first point on first line
322     * @param p2 second point on first line
323     * @param p3 first point on second line
324     * @param p4 second point on second line
325     * @return EastNorth null if no intersection was found, the coordinates of the intersection otherwise
326     * @throws IllegalArgumentException if a parameter is null or without valid coordinates
327     */
328    public static EastNorth getLineLineIntersection(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) {
329
330        CheckParameterUtil.ensureValidCoordinates(p1, "p1");
331        CheckParameterUtil.ensureValidCoordinates(p2, "p2");
332        CheckParameterUtil.ensureValidCoordinates(p3, "p3");
333        CheckParameterUtil.ensureValidCoordinates(p4, "p4");
334
335        if (!p1.isValid()) throw new IllegalArgumentException(p1+" is invalid");
336
337        // Basically, the formula from wikipedia is used:
338        //  https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
339        // However, large numbers lead to rounding errors (see #10286).
340        // To avoid this, p1 is first substracted from each of the points:
341        //  p1' = 0
342        //  p2' = p2 - p1
343        //  p3' = p3 - p1
344        //  p4' = p4 - p1
345        // In the end, p1 is added to the intersection point of segment p1'/p2'
346        // and segment p3'/p4'.
347
348        // Convert line from (point, point) form to ax+by=c
349        double a1 = p2.getY() - p1.getY();
350        double b1 = p1.getX() - p2.getX();
351
352        double a2 = p4.getY() - p3.getY();
353        double b2 = p3.getX() - p4.getX();
354        double c2 = (p4.getX() - p1.getX()) * (p3.getY() - p1.getY()) - (p3.getX() - p1.getX()) * (p4.getY() - p1.getY());
355
356        // Solve the equations
357        double det = a1 * b2 - a2 * b1;
358        if (det == 0)
359            return null; // Lines are parallel
360
361        return new EastNorth(b1 * c2 / det + p1.getX(), -a1 * c2 / det + p1.getY());
362    }
363
364    public static boolean segmentsParallel(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) {
365
366        CheckParameterUtil.ensureValidCoordinates(p1, "p1");
367        CheckParameterUtil.ensureValidCoordinates(p2, "p2");
368        CheckParameterUtil.ensureValidCoordinates(p3, "p3");
369        CheckParameterUtil.ensureValidCoordinates(p4, "p4");
370
371        // Convert line from (point, point) form to ax+by=c
372        double a1 = p2.getY() - p1.getY();
373        double b1 = p1.getX() - p2.getX();
374
375        double a2 = p4.getY() - p3.getY();
376        double b2 = p3.getX() - p4.getX();
377
378        // Solve the equations
379        double det = a1 * b2 - a2 * b1;
380        // remove influence of of scaling factor
381        det /= Math.sqrt(a1*a1 + b1*b1) * Math.sqrt(a2*a2 + b2*b2);
382        return Math.abs(det) < 1e-3;
383    }
384
385    private static EastNorth closestPointTo(EastNorth p1, EastNorth p2, EastNorth point, boolean segmentOnly) {
386        CheckParameterUtil.ensureParameterNotNull(p1, "p1");
387        CheckParameterUtil.ensureParameterNotNull(p2, "p2");
388        CheckParameterUtil.ensureParameterNotNull(point, "point");
389
390        double ldx = p2.getX() - p1.getX();
391        double ldy = p2.getY() - p1.getY();
392
393        //segment zero length
394        if (ldx == 0 && ldy == 0)
395            return p1;
396
397        double pdx = point.getX() - p1.getX();
398        double pdy = point.getY() - p1.getY();
399
400        double offset = (pdx * ldx + pdy * ldy) / (ldx * ldx + ldy * ldy);
401
402        if (segmentOnly && offset <= 0)
403            return p1;
404        else if (segmentOnly && offset >= 1)
405            return p2;
406        else
407            return new EastNorth(p1.getX() + ldx * offset, p1.getY() + ldy * offset);
408    }
409
410    /**
411     * Calculates closest point to a line segment.
412     * @param segmentP1 First point determining line segment
413     * @param segmentP2 Second point determining line segment
414     * @param point Point for which a closest point is searched on line segment [P1,P2]
415     * @return segmentP1 if it is the closest point, segmentP2 if it is the closest point,
416     * a new point if closest point is between segmentP1 and segmentP2.
417     * @see #closestPointToLine
418     * @since 3650
419     */
420    public static EastNorth closestPointToSegment(EastNorth segmentP1, EastNorth segmentP2, EastNorth point) {
421        return closestPointTo(segmentP1, segmentP2, point, true);
422    }
423
424    /**
425     * Calculates closest point to a line.
426     * @param lineP1 First point determining line
427     * @param lineP2 Second point determining line
428     * @param point Point for which a closest point is searched on line (P1,P2)
429     * @return The closest point found on line. It may be outside the segment [P1,P2].
430     * @see #closestPointToSegment
431     * @since 4134
432     */
433    public static EastNorth closestPointToLine(EastNorth lineP1, EastNorth lineP2, EastNorth point) {
434        return closestPointTo(lineP1, lineP2, point, false);
435    }
436
437    /**
438     * This method tests if secondNode is clockwise to first node.
439     *
440     * The line through the two points commonNode and firstNode divides the
441     * plane into two parts. The test returns true, if secondNode lies in
442     * the part that is to the right when traveling in the direction from
443     * commonNode to firstNode.
444     *
445     * @param commonNode starting point for both vectors
446     * @param firstNode first vector end node
447     * @param secondNode second vector end node
448     * @return true if first vector is clockwise before second vector.
449     */
450    public static boolean angleIsClockwise(EastNorth commonNode, EastNorth firstNode, EastNorth secondNode) {
451
452        CheckParameterUtil.ensureValidCoordinates(commonNode, "commonNode");
453        CheckParameterUtil.ensureValidCoordinates(firstNode, "firstNode");
454        CheckParameterUtil.ensureValidCoordinates(secondNode, "secondNode");
455
456        double dy1 = firstNode.getY() - commonNode.getY();
457        double dy2 = secondNode.getY() - commonNode.getY();
458        double dx1 = firstNode.getX() - commonNode.getX();
459        double dx2 = secondNode.getX() - commonNode.getX();
460
461        return dy1 * dx2 - dx1 * dy2 > 0;
462    }
463
464    /**
465     * Returns the Area of a polygon, from its list of nodes.
466     * @param polygon List of nodes forming polygon (EastNorth coordinates)
467     * @return Area for the given list of nodes
468     * @since 6841
469     */
470    public static Area getArea(List<Node> polygon) {
471        Path2D path = new Path2D.Double();
472
473        boolean begin = true;
474        for (Node n : polygon) {
475            EastNorth en = n.getEastNorth();
476            if (en != null) {
477                if (begin) {
478                    path.moveTo(en.getX(), en.getY());
479                    begin = false;
480                } else {
481                    path.lineTo(en.getX(), en.getY());
482                }
483            }
484        }
485        if (!begin) {
486            path.closePath();
487        }
488
489        return new Area(path);
490    }
491
492    /**
493     * Returns the Area of a polygon, from its list of nodes.
494     * @param polygon List of nodes forming polygon (LatLon coordinates)
495     * @return Area for the given list of nodes
496     * @since 6841
497     */
498    public static Area getAreaLatLon(List<Node> polygon) {
499        Path2D path = new Path2D.Double();
500
501        boolean begin = true;
502        for (Node n : polygon) {
503            if (begin) {
504                path.moveTo(n.getCoor().lon(), n.getCoor().lat());
505                begin = false;
506            } else {
507                path.lineTo(n.getCoor().lon(), n.getCoor().lat());
508            }
509        }
510        if (!begin) {
511            path.closePath();
512        }
513
514        return new Area(path);
515    }
516
517    /**
518     * Tests if two polygons intersect.
519     * @param first List of nodes forming first polygon
520     * @param second List of nodes forming second polygon
521     * @return intersection kind
522     */
523    public static PolygonIntersection polygonIntersection(List<Node> first, List<Node> second) {
524        Area a1 = getArea(first);
525        Area a2 = getArea(second);
526        return polygonIntersection(a1, a2);
527    }
528
529    /**
530     * Tests if two polygons intersect.
531     * @param a1 Area of first polygon
532     * @param a2 Area of second polygon
533     * @return intersection kind
534     * @since 6841
535     */
536    public static PolygonIntersection polygonIntersection(Area a1, Area a2) {
537        return polygonIntersection(a1, a2, 1.0);
538    }
539
540    /**
541     * Tests if two polygons intersect.
542     * @param a1 Area of first polygon
543     * @param a2 Area of second polygon
544     * @param eps an area threshold, everything below is considered an empty intersection
545     * @return intersection kind
546     */
547    public static PolygonIntersection polygonIntersection(Area a1, Area a2, double eps) {
548
549        Area inter = new Area(a1);
550        inter.intersect(a2);
551
552        Rectangle bounds = inter.getBounds();
553
554        if (inter.isEmpty() || bounds.getHeight()*bounds.getWidth() <= eps) {
555            return PolygonIntersection.OUTSIDE;
556        } else if (inter.equals(a1)) {
557            return PolygonIntersection.FIRST_INSIDE_SECOND;
558        } else if (inter.equals(a2)) {
559            return PolygonIntersection.SECOND_INSIDE_FIRST;
560        } else {
561            return PolygonIntersection.CROSSING;
562        }
563    }
564
565    /**
566     * Tests if point is inside a polygon. The polygon can be self-intersecting. In such case the contains function works in xor-like manner.
567     * @param polygonNodes list of nodes from polygon path.
568     * @param point the point to test
569     * @return true if the point is inside polygon.
570     */
571    public static boolean nodeInsidePolygon(Node point, List<Node> polygonNodes) {
572        if (polygonNodes.size() < 2)
573            return false;
574
575        boolean inside = false;
576        Node p1, p2;
577
578        //iterate each side of the polygon, start with the last segment
579        Node oldPoint = polygonNodes.get(polygonNodes.size() - 1);
580
581        if (!oldPoint.isLatLonKnown()) {
582            return false;
583        }
584
585        for (Node newPoint : polygonNodes) {
586            //skip duplicate points
587            if (newPoint.equals(oldPoint)) {
588                continue;
589            }
590
591            if (!newPoint.isLatLonKnown()) {
592                return false;
593            }
594
595            //order points so p1.lat <= p2.lat
596            if (newPoint.getEastNorth().getY() > oldPoint.getEastNorth().getY()) {
597                p1 = oldPoint;
598                p2 = newPoint;
599            } else {
600                p1 = newPoint;
601                p2 = oldPoint;
602            }
603
604            EastNorth pEN = point.getEastNorth();
605            EastNorth opEN = oldPoint.getEastNorth();
606            EastNorth npEN = newPoint.getEastNorth();
607            EastNorth p1EN = p1.getEastNorth();
608            EastNorth p2EN = p2.getEastNorth();
609
610            if (pEN != null && opEN != null && npEN != null && p1EN != null && p2EN != null) {
611                //test if the line is crossed and if so invert the inside flag.
612                if ((npEN.getY() < pEN.getY()) == (pEN.getY() <= opEN.getY())
613                        && (pEN.getX() - p1EN.getX()) * (p2EN.getY() - p1EN.getY())
614                        < (p2EN.getX() - p1EN.getX()) * (pEN.getY() - p1EN.getY())) {
615                    inside = !inside;
616                }
617            }
618
619            oldPoint = newPoint;
620        }
621
622        return inside;
623    }
624
625    /**
626     * Returns area of a closed way in square meters.
627     * (approximate(?), but should be OK for small areas)
628     *
629     * Relies on the current projection: Works correctly, when
630     * one unit in projected coordinates corresponds to one meter.
631     * This is true for most projections, but not for WGS84 and
632     * Mercator (EPSG:3857).
633     *
634     * @param way Way to measure, should be closed (first node is the same as last node)
635     * @return area of the closed way.
636     */
637    public static double closedWayArea(Way way) {
638
639        //http://local.wasp.uwa.edu.au/~pbourke/geometry/polyarea/
640        double area = 0;
641        Node lastN = null;
642        for (Node n : way.getNodes()) {
643            if (lastN != null) {
644                area += (calcX(n) * calcY(lastN)) - (calcY(n) * calcX(lastN));
645            }
646            lastN = n;
647        }
648        return Math.abs(area/2);
649    }
650
651    protected static double calcX(Node p1) {
652        double lat1, lon1, lat2, lon2;
653        double dlon, dlat;
654
655        lat1 = p1.getCoor().lat() * Math.PI / 180.0;
656        lon1 = p1.getCoor().lon() * Math.PI / 180.0;
657        lat2 = lat1;
658        lon2 = 0;
659
660        dlon = lon2 - lon1;
661        dlat = lat2 - lat1;
662
663        double a = Math.pow(Math.sin(dlat/2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon/2), 2);
664        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
665        return 6367000 * c;
666    }
667
668    protected static double calcY(Node p1) {
669        double lat1, lon1, lat2, lon2;
670        double dlon, dlat;
671
672        lat1 = p1.getCoor().lat() * Math.PI / 180.0;
673        lon1 = p1.getCoor().lon() * Math.PI / 180.0;
674        lat2 = 0;
675        lon2 = lon1;
676
677        dlon = lon2 - lon1;
678        dlat = lat2 - lat1;
679
680        double a = Math.pow(Math.sin(dlat/2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon/2), 2);
681        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
682        return 6367000 * c;
683    }
684
685    /**
686     * Determines whether a way is oriented clockwise.
687     *
688     * Internals: Assuming a closed non-looping way, compute twice the area
689     * of the polygon using the formula {@code 2 * area = sum (X[n] * Y[n+1] - X[n+1] * Y[n])}.
690     * If the area is negative the way is ordered in a clockwise direction.
691     *
692     * See http://paulbourke.net/geometry/polyarea/
693     *
694     * @param w the way to be checked.
695     * @return true if and only if way is oriented clockwise.
696     * @throws IllegalArgumentException if way is not closed (see {@link Way#isClosed}).
697     */
698    public static boolean isClockwise(Way w) {
699        return isClockwise(w.getNodes());
700    }
701
702    /**
703     * Determines whether path from nodes list is oriented clockwise.
704     * @param nodes Nodes list to be checked.
705     * @return true if and only if way is oriented clockwise.
706     * @throws IllegalArgumentException if way is not closed (see {@link Way#isClosed}).
707     * @see #isClockwise(Way)
708     */
709    public static boolean isClockwise(List<Node> nodes) {
710        double area2 = 0.;
711        int nodesCount = nodes.size();
712        if (nodesCount < 3 || nodes.get(0) != nodes.get(nodesCount - 1)) {
713            throw new IllegalArgumentException("Way must be closed to check orientation.");
714        }
715
716        for (int node = 1; node <= /*sic! consider last-first as well*/ nodesCount; node++) {
717            LatLon coorPrev = nodes.get(node - 1).getCoor();
718            LatLon coorCurr = nodes.get(node % nodesCount).getCoor();
719            area2 += coorPrev.lon() * coorCurr.lat();
720            area2 -= coorCurr.lon() * coorPrev.lat();
721        }
722        return area2 < 0;
723    }
724
725    /**
726     * Returns angle of a segment defined with 2 point coordinates.
727     *
728     * @param p1 first point
729     * @param p2 second point
730     * @return Angle in radians (-pi, pi]
731     */
732    public static double getSegmentAngle(EastNorth p1, EastNorth p2) {
733
734        CheckParameterUtil.ensureValidCoordinates(p1, "p1");
735        CheckParameterUtil.ensureValidCoordinates(p2, "p2");
736
737        return Math.atan2(p2.north() - p1.north(), p2.east() - p1.east());
738    }
739
740    /**
741     * Returns angle of a corner defined with 3 point coordinates.
742     *
743     * @param p1 first point
744     * @param p2 Common endpoint
745     * @param p3 third point
746     * @return Angle in radians (-pi, pi]
747     */
748    public static double getCornerAngle(EastNorth p1, EastNorth p2, EastNorth p3) {
749
750        CheckParameterUtil.ensureValidCoordinates(p1, "p1");
751        CheckParameterUtil.ensureValidCoordinates(p2, "p2");
752        CheckParameterUtil.ensureValidCoordinates(p3, "p3");
753
754        Double result = getSegmentAngle(p2, p1) - getSegmentAngle(p2, p3);
755        if (result <= -Math.PI) {
756            result += 2 * Math.PI;
757        }
758
759        if (result > Math.PI) {
760            result -= 2 * Math.PI;
761        }
762
763        return result;
764    }
765
766    /**
767     * Compute the centroid/barycenter of nodes
768     * @param nodes Nodes for which the centroid is wanted
769     * @return the centroid of nodes
770     * @see Geometry#getCenter
771     */
772    public static EastNorth getCentroid(List<Node> nodes) {
773
774        BigDecimal area = BigDecimal.ZERO;
775        BigDecimal north = BigDecimal.ZERO;
776        BigDecimal east = BigDecimal.ZERO;
777
778        // See https://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon for the equation used here
779        for (int i = 0; i < nodes.size(); i++) {
780            EastNorth n0 = nodes.get(i).getEastNorth();
781            EastNorth n1 = nodes.get((i+1) % nodes.size()).getEastNorth();
782
783            if (n0 != null && n1 != null && n0.isValid() && n1.isValid()) {
784                BigDecimal x0 = BigDecimal.valueOf(n0.east());
785                BigDecimal y0 = BigDecimal.valueOf(n0.north());
786                BigDecimal x1 = BigDecimal.valueOf(n1.east());
787                BigDecimal y1 = BigDecimal.valueOf(n1.north());
788
789                BigDecimal k = x0.multiply(y1, MathContext.DECIMAL128).subtract(y0.multiply(x1, MathContext.DECIMAL128));
790
791                area = area.add(k, MathContext.DECIMAL128);
792                east = east.add(k.multiply(x0.add(x1, MathContext.DECIMAL128), MathContext.DECIMAL128));
793                north = north.add(k.multiply(y0.add(y1, MathContext.DECIMAL128), MathContext.DECIMAL128));
794            }
795        }
796
797        BigDecimal d = new BigDecimal(3, MathContext.DECIMAL128); // 1/2 * 6 = 3
798        area  = area.multiply(d, MathContext.DECIMAL128);
799        if (area.compareTo(BigDecimal.ZERO) != 0) {
800            north = north.divide(area, MathContext.DECIMAL128);
801            east = east.divide(area, MathContext.DECIMAL128);
802        }
803
804        return new EastNorth(east.doubleValue(), north.doubleValue());
805    }
806
807    /**
808     * Compute center of the circle closest to different nodes.
809     *
810     * Ensure exact center computation in case nodes are already aligned in circle.
811     * This is done by least square method.
812     * Let be a_i x + b_i y + c_i = 0 equations of bisectors of each edges.
813     * Center must be intersection of all bisectors.
814     * <pre>
815     *          [ a1  b1  ]         [ -c1 ]
816     * With A = [ ... ... ] and Y = [ ... ]
817     *          [ an  bn  ]         [ -cn ]
818     * </pre>
819     * An approximation of center of circle is (At.A)^-1.At.Y
820     * @param nodes Nodes parts of the circle (at least 3)
821     * @return An approximation of the center, of null if there is no solution.
822     * @see Geometry#getCentroid
823     * @since 6934
824     */
825    public static EastNorth getCenter(List<Node> nodes) {
826        int nc = nodes.size();
827        if (nc < 3) return null;
828        /**
829         * Equation of each bisector ax + by + c = 0
830         */
831        double[] a = new double[nc];
832        double[] b = new double[nc];
833        double[] c = new double[nc];
834        // Compute equation of bisector
835        for (int i = 0; i < nc; i++) {
836            EastNorth pt1 = nodes.get(i).getEastNorth();
837            EastNorth pt2 = nodes.get((i+1) % nc).getEastNorth();
838            a[i] = pt1.east() - pt2.east();
839            b[i] = pt1.north() - pt2.north();
840            double d = Math.sqrt(a[i]*a[i] + b[i]*b[i]);
841            if (d == 0) return null;
842            a[i] /= d;
843            b[i] /= d;
844            double xC = (pt1.east() + pt2.east()) / 2;
845            double yC = (pt1.north() + pt2.north()) / 2;
846            c[i] = -(a[i]*xC + b[i]*yC);
847        }
848        // At.A = [aij]
849        double a11 = 0, a12 = 0, a22 = 0;
850        // At.Y = [bi]
851        double b1 = 0, b2 = 0;
852        for (int i = 0; i < nc; i++) {
853            a11 += a[i]*a[i];
854            a12 += a[i]*b[i];
855            a22 += b[i]*b[i];
856            b1 -= a[i]*c[i];
857            b2 -= b[i]*c[i];
858        }
859        // (At.A)^-1 = [invij]
860        double det = a11*a22 - a12*a12;
861        if (Math.abs(det) < 1e-5) return null;
862        double inv11 = a22/det;
863        double inv12 = -a12/det;
864        double inv22 = a11/det;
865        // center (xC, yC) = (At.A)^-1.At.y
866        double xC = inv11*b1 + inv12*b2;
867        double yC = inv12*b1 + inv22*b2;
868        return new EastNorth(xC, yC);
869    }
870
871    public static class MultiPolygonMembers {
872        public final Set<Way> outers = new HashSet<>();
873        public final Set<Way> inners = new HashSet<>();
874
875        public MultiPolygonMembers(Relation multiPolygon) {
876            for (RelationMember m : multiPolygon.getMembers()) {
877                if (m.getType().equals(OsmPrimitiveType.WAY)) {
878                    if ("outer".equals(m.getRole())) {
879                        outers.add(m.getWay());
880                    } else if ("inner".equals(m.getRole())) {
881                        inners.add(m.getWay());
882                    }
883                }
884            }
885        }
886    }
887
888    /**
889     * Tests if the {@code node} is inside the multipolygon {@code multiPolygon}. The nullable argument
890     * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match.
891     * @param node node
892     * @param multiPolygon multipolygon
893     * @param isOuterWayAMatch allows to decide if the immediate {@code outer} way of the multipolygon is a match
894     * @return {@code true} if the node is inside the multipolygon
895     */
896    public static boolean isNodeInsideMultiPolygon(Node node, Relation multiPolygon, Predicate<Way> isOuterWayAMatch) {
897        return isPolygonInsideMultiPolygon(Collections.singletonList(node), multiPolygon, isOuterWayAMatch);
898    }
899
900    /**
901     * Tests if the polygon formed by {@code nodes} is inside the multipolygon {@code multiPolygon}. The nullable argument
902     * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match.
903     * <p>
904     * If {@code nodes} contains exactly one element, then it is checked whether that one node is inside the multipolygon.
905     * @param nodes nodes forming the polygon
906     * @param multiPolygon multipolygon
907     * @param isOuterWayAMatch allows to decide if the immediate {@code outer} way of the multipolygon is a match
908     * @return {@code true} if the polygon formed by nodes is inside the multipolygon
909     */
910    public static boolean isPolygonInsideMultiPolygon(List<Node> nodes, Relation multiPolygon, Predicate<Way> isOuterWayAMatch) {
911        // Extract outer/inner members from multipolygon
912        final MultiPolygonMembers mpm = new MultiPolygonMembers(multiPolygon);
913        // Construct complete rings for the inner/outer members
914        final List<MultipolygonBuilder.JoinedPolygon> outerRings;
915        final List<MultipolygonBuilder.JoinedPolygon> innerRings;
916        try {
917            outerRings = MultipolygonBuilder.joinWays(mpm.outers);
918            innerRings = MultipolygonBuilder.joinWays(mpm.inners);
919        } catch (MultipolygonBuilder.JoinedPolygonCreationException ex) {
920            Main.debug("Invalid multipolygon " + multiPolygon);
921            return false;
922        }
923        // Test if object is inside an outer member
924        for (MultipolygonBuilder.JoinedPolygon out : outerRings) {
925            if (nodes.size() == 1
926                    ? nodeInsidePolygon(nodes.get(0), out.getNodes())
927                    : EnumSet.of(PolygonIntersection.FIRST_INSIDE_SECOND, PolygonIntersection.CROSSING).contains(
928                            polygonIntersection(nodes, out.getNodes()))) {
929                boolean insideInner = false;
930                // If inside an outer, check it is not inside an inner
931                for (MultipolygonBuilder.JoinedPolygon in : innerRings) {
932                    if (polygonIntersection(in.getNodes(), out.getNodes()) == PolygonIntersection.FIRST_INSIDE_SECOND
933                            && (nodes.size() == 1
934                            ? nodeInsidePolygon(nodes.get(0), in.getNodes())
935                            : polygonIntersection(nodes, in.getNodes()) == PolygonIntersection.FIRST_INSIDE_SECOND)) {
936                        insideInner = true;
937                        break;
938                    }
939                }
940                // Inside outer but not inside inner -> the polygon appears to be inside a the multipolygon
941                if (!insideInner) {
942                    // Final check using predicate
943                    if (isOuterWayAMatch == null || isOuterWayAMatch.evaluate(out.ways.get(0)
944                            /* TODO give a better representation of the outer ring to the predicate */)) {
945                        return true;
946                    }
947                }
948            }
949        }
950        return false;
951    }
952}