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