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