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