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