001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.tools; 003 004import static org.openstreetmap.josm.data.projection.Ellipsoid.WGS84; 005 006import java.awt.geom.Area; 007import java.awt.geom.Line2D; 008import java.awt.geom.Path2D; 009import java.awt.geom.PathIterator; 010import java.awt.geom.Rectangle2D; 011import java.math.BigDecimal; 012import java.math.MathContext; 013import java.util.ArrayList; 014import java.util.Collection; 015import java.util.Collections; 016import java.util.Comparator; 017import java.util.Iterator; 018import java.util.LinkedHashSet; 019import java.util.List; 020import java.util.Map; 021import java.util.Set; 022import java.util.TreeSet; 023import java.util.function.Predicate; 024import java.util.stream.Collectors; 025 026import org.openstreetmap.josm.command.AddCommand; 027import org.openstreetmap.josm.command.ChangeNodesCommand; 028import org.openstreetmap.josm.command.Command; 029import org.openstreetmap.josm.data.coor.EastNorth; 030import org.openstreetmap.josm.data.coor.ILatLon; 031import org.openstreetmap.josm.data.coor.LatLon; 032import org.openstreetmap.josm.data.osm.BBox; 033import org.openstreetmap.josm.data.osm.DataSet; 034import org.openstreetmap.josm.data.osm.INode; 035import org.openstreetmap.josm.data.osm.IPrimitive; 036import org.openstreetmap.josm.data.osm.IRelation; 037import org.openstreetmap.josm.data.osm.IWay; 038import org.openstreetmap.josm.data.osm.MultipolygonBuilder; 039import org.openstreetmap.josm.data.osm.MultipolygonBuilder.JoinedPolygon; 040import org.openstreetmap.josm.data.osm.Node; 041import org.openstreetmap.josm.data.osm.NodePositionComparator; 042import org.openstreetmap.josm.data.osm.OsmPrimitive; 043import org.openstreetmap.josm.data.osm.Relation; 044import org.openstreetmap.josm.data.osm.Way; 045import org.openstreetmap.josm.data.osm.WaySegment; 046import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon; 047import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon.PolyData; 048import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache; 049import org.openstreetmap.josm.data.projection.Projection; 050import org.openstreetmap.josm.data.projection.ProjectionRegistry; 051import org.openstreetmap.josm.data.projection.Projections; 052 053/** 054 * Some tools for geometry related tasks. 055 * 056 * @author viesturs 057 */ 058public final class Geometry { 059 060 private Geometry() { 061 // Hide default constructor for utils classes 062 } 063 064 /** 065 * The result types for a {@link Geometry#polygonIntersection(Area, Area)} test 066 */ 067 public enum PolygonIntersection { 068 /** 069 * The first polygon is inside the second one 070 */ 071 FIRST_INSIDE_SECOND, 072 /** 073 * The second one is inside the first 074 */ 075 SECOND_INSIDE_FIRST, 076 /** 077 * The polygons do not overlap 078 */ 079 OUTSIDE, 080 /** 081 * The polygon borders cross each other 082 */ 083 CROSSING 084 } 085 086 /** threshold value for size of intersection area given in east/north space */ 087 public static final double INTERSECTION_EPS_EAST_NORTH = 1e-4; 088 089 private static final String INVALID_COORDINATE_MSG = " invalid"; 090 091 /** 092 * Will find all intersection and add nodes there for list of given ways. 093 * Handles self-intersections too. 094 * And makes commands to add the intersection points to ways. 095 * <p> 096 * Prerequisite: no two nodes have the same coordinates. 097 * 098 * @param ways a list of ways to test 099 * @param test if true, do not build list of Commands, just return nodes 100 * @param cmds list of commands, typically empty when handed to this method. 101 * Will be filled with commands that add intersection nodes to 102 * the ways. 103 * @return set of new nodes, if test is true the list might not contain all intersections 104 */ 105 public static Set<Node> addIntersections(List<Way> ways, boolean test, List<Command> cmds) { 106 107 final int n = ways.size(); 108 @SuppressWarnings("unchecked") 109 final 110 List<Node>[] newNodes = new ArrayList[n]; 111 final BBox[] wayBounds = new BBox[n]; 112 final boolean[] changedWays = new boolean[n]; 113 114 final Set<Node> intersectionNodes = new LinkedHashSet<>(); 115 116 //copy node arrays for local usage. 117 for (int pos = 0; pos < n; pos++) { 118 newNodes[pos] = new ArrayList<>(ways.get(pos).getNodes()); 119 wayBounds[pos] = ways.get(pos).getBBox(); 120 changedWays[pos] = false; 121 } 122 123 final DataSet dataset = ways.get(0).getDataSet(); 124 125 //iterate over all way pairs and introduce the intersections 126 final Comparator<Node> coordsComparator = new NodePositionComparator(); 127 for (int seg1Way = 0; seg1Way < n; seg1Way++) { 128 for (int seg2Way = seg1Way; seg2Way < n; seg2Way++) { 129 130 //do not waste time on bounds that do not intersect 131 if (!wayBounds[seg1Way].intersects(wayBounds[seg2Way])) { 132 continue; 133 } 134 135 final List<Node> way1Nodes = newNodes[seg1Way]; 136 final List<Node> way2Nodes = newNodes[seg2Way]; 137 138 //iterate over primary segment 139 for (int seg1Pos = 0; seg1Pos + 1 < way1Nodes.size(); seg1Pos++) { 140 141 //iterate over secondary segment 142 final int seg2Start = seg1Way != seg2Way ? 0 : seg1Pos + 2; //skip the adjacent segment 143 144 for (int seg2Pos = seg2Start; seg2Pos + 1 < way2Nodes.size(); seg2Pos++) { 145 146 //need to get them again every time, because other segments may be changed 147 final Node seg1Node1 = way1Nodes.get(seg1Pos); 148 final Node seg1Node2 = way1Nodes.get(seg1Pos + 1); 149 final Node seg2Node1 = way2Nodes.get(seg2Pos); 150 final Node seg2Node2 = way2Nodes.get(seg2Pos + 1); 151 152 int commonCount = 0; 153 //test if we have common nodes to add. 154 if (seg1Node1 == seg2Node1 || seg1Node1 == seg2Node2) { 155 commonCount++; 156 157 if (seg1Way == seg2Way && 158 seg1Pos == 0 && 159 seg2Pos == way2Nodes.size() -2) { 160 //do not add - this is first and last segment of the same way. 161 } else { 162 intersectionNodes.add(seg1Node1); 163 } 164 } 165 166 if (seg1Node2 == seg2Node1 || seg1Node2 == seg2Node2) { 167 commonCount++; 168 169 intersectionNodes.add(seg1Node2); 170 } 171 172 //no common nodes - find intersection 173 if (commonCount == 0) { 174 final EastNorth intersection = getSegmentSegmentIntersection( 175 seg1Node1.getEastNorth(), seg1Node2.getEastNorth(), 176 seg2Node1.getEastNorth(), seg2Node2.getEastNorth()); 177 178 if (intersection != null) { 179 final Node newNode = new Node(ProjectionRegistry.getProjection().eastNorth2latlon(intersection)); 180 Node intNode = newNode; 181 boolean insertInSeg1 = false; 182 boolean insertInSeg2 = false; 183 //find if the intersection point is at end point of one of the segments, if so use that point 184 185 //segment 1 186 if (coordsComparator.compare(newNode, seg1Node1) == 0) { 187 intNode = seg1Node1; 188 } else if (coordsComparator.compare(newNode, seg1Node2) == 0) { 189 intNode = seg1Node2; 190 } else { 191 insertInSeg1 = true; 192 } 193 194 //segment 2 195 if (coordsComparator.compare(newNode, seg2Node1) == 0) { 196 intNode = seg2Node1; 197 } else if (coordsComparator.compare(newNode, seg2Node2) == 0) { 198 intNode = seg2Node2; 199 } else { 200 insertInSeg2 = true; 201 } 202 203 if (test) { 204 intersectionNodes.add(intNode); 205 return intersectionNodes; 206 } 207 208 if (insertInSeg1) { 209 way1Nodes.add(seg1Pos +1, intNode); 210 changedWays[seg1Way] = true; 211 212 //fix seg2 position, as indexes have changed, seg2Pos is always bigger than seg1Pos on the same segment. 213 if (seg2Way == seg1Way) { 214 seg2Pos++; 215 } 216 } 217 218 if (insertInSeg2) { 219 way2Nodes.add(seg2Pos +1, intNode); 220 changedWays[seg2Way] = true; 221 222 //Do not need to compare again to already split segment 223 seg2Pos++; 224 } 225 226 intersectionNodes.add(intNode); 227 228 if (intNode == newNode) { 229 cmds.add(new AddCommand(dataset, intNode)); 230 } 231 } 232 } else if (test && !intersectionNodes.isEmpty()) { 233 return intersectionNodes; 234 } 235 } 236 } 237 } 238 } 239 240 241 for (int pos = 0; pos < ways.size(); pos++) { 242 if (changedWays[pos]) { 243 cmds.add(new ChangeNodesCommand(dataset, ways.get(pos), newNodes[pos])); 244 } 245 } 246 247 return intersectionNodes; 248 } 249 250 /** 251 * Tests if given point is to the right side of path consisting of 3 points. 252 * <p> 253 * (Imagine the path is continued beyond the endpoints, so you get two rays 254 * starting from lineP2 and going through lineP1 and lineP3 respectively 255 * which divide the plane into two parts. The test returns true, if testPoint 256 * lies in the part that is to the right when traveling in the direction 257 * lineP1, lineP2, lineP3.) 258 * 259 * @param <N> type of node 260 * @param lineP1 first point in path 261 * @param lineP2 second point in path 262 * @param lineP3 third point in path 263 * @param testPoint point to test 264 * @return true if to the right side, false otherwise 265 */ 266 public static <N extends INode> boolean isToTheRightSideOfLine(N lineP1, N lineP2, N lineP3, N testPoint) { 267 final boolean pathBendToRight = angleIsClockwise(lineP1, lineP2, lineP3); 268 final boolean rightOfSeg1 = angleIsClockwise(lineP1, lineP2, testPoint); 269 final boolean rightOfSeg2 = angleIsClockwise(lineP2, lineP3, testPoint); 270 271 if (pathBendToRight) { 272 return rightOfSeg1 && rightOfSeg2; 273 } else { 274 return !(!rightOfSeg1 && !rightOfSeg2); 275 } 276 } 277 278 /** 279 * This method tests if secondNode is clockwise to first node. 280 * @param <N> type of node 281 * @param commonNode starting point for both vectors 282 * @param firstNode first vector end node 283 * @param secondNode second vector end node 284 * @return true if first vector is clockwise before second vector. 285 */ 286 public static <N extends INode> boolean angleIsClockwise(N commonNode, N firstNode, N secondNode) { 287 return angleIsClockwise(commonNode.getEastNorth(), firstNode.getEastNorth(), secondNode.getEastNorth()); 288 } 289 290 /** 291 * Finds the intersection of two line segments. 292 * @param p1 the coordinates of the start point of the first specified line segment 293 * @param p2 the coordinates of the end point of the first specified line segment 294 * @param p3 the coordinates of the start point of the second specified line segment 295 * @param p4 the coordinates of the end point of the second specified line segment 296 * @return EastNorth null if no intersection was found, the EastNorth coordinates of the intersection otherwise 297 * @see #getSegmentSegmentIntersection(ILatLon, ILatLon, ILatLon, ILatLon) 298 */ 299 public static EastNorth getSegmentSegmentIntersection(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) { 300 // see the ILatLon version for an explanation why the checks are in the if statement 301 if (!(p1.isValid() && p2.isValid() && p3.isValid() && p4.isValid())) { 302 CheckParameterUtil.ensureThat(p1.isValid(), () -> p1 + INVALID_COORDINATE_MSG); 303 CheckParameterUtil.ensureThat(p2.isValid(), () -> p2 + INVALID_COORDINATE_MSG); 304 CheckParameterUtil.ensureThat(p3.isValid(), () -> p3 + INVALID_COORDINATE_MSG); 305 CheckParameterUtil.ensureThat(p4.isValid(), () -> p4 + INVALID_COORDINATE_MSG); 306 } 307 308 final double x1 = p1.getX(); 309 final double y1 = p1.getY(); 310 final double x2 = p2.getX(); 311 final double y2 = p2.getY(); 312 final double x3 = p3.getX(); 313 final double y3 = p3.getY(); 314 final double x4 = p4.getX(); 315 final double y4 = p4.getY(); 316 final double[] en = getSegmentSegmentIntersection(x1, y1, x2, y2, x3, y3, x4, y4); 317 if (en != null && en.length == 2) { 318 return new EastNorth(en[0], en[1]); 319 } 320 return null; 321 } 322 323 /** 324 * Finds the intersection of two line segments. 325 * @param p1 the coordinates of the start point of the first specified line segment 326 * @param p2 the coordinates of the end point of the first specified line segment 327 * @param p3 the coordinates of the start point of the second specified line segment 328 * @param p4 the coordinates of the end point of the second specified line segment 329 * @return LatLon null if no intersection was found, the LatLon coordinates of the intersection otherwise 330 * @see #getSegmentSegmentIntersection(EastNorth, EastNorth, EastNorth, EastNorth) 331 * @since 18553 332 */ 333 public static ILatLon getSegmentSegmentIntersection(ILatLon p1, ILatLon p2, ILatLon p3, ILatLon p4) { 334 // Avoid lambda creation if at all possible -- this pretty much removes all memory allocations 335 // from this method (11.4 GB to 0) when testing #20716 with Mesa County, CO (overpass download). 336 // There was also a 2/3 decrease in CPU samples for the method. 337 if (!(p1.isLatLonKnown() && p2.isLatLonKnown() && p3.isLatLonKnown() && p4.isLatLonKnown())) { 338 CheckParameterUtil.ensureThat(p1.isLatLonKnown(), () -> p1 + INVALID_COORDINATE_MSG); 339 CheckParameterUtil.ensureThat(p2.isLatLonKnown(), () -> p2 + INVALID_COORDINATE_MSG); 340 CheckParameterUtil.ensureThat(p3.isLatLonKnown(), () -> p3 + INVALID_COORDINATE_MSG); 341 CheckParameterUtil.ensureThat(p4.isLatLonKnown(), () -> p4 + INVALID_COORDINATE_MSG); 342 } 343 344 final double x1 = p1.lon(); 345 final double y1 = p1.lat(); 346 final double x2 = p2.lon(); 347 final double y2 = p2.lat(); 348 final double x3 = p3.lon(); 349 final double y3 = p3.lat(); 350 final double x4 = p4.lon(); 351 final double y4 = p4.lat(); 352 final double[] en = getSegmentSegmentIntersection(x1, y1, x2, y2, x3, y3, x4, y4); 353 if (en != null && en.length == 2) { 354 return new LatLon(en[1], en[0]); 355 } 356 return null; 357 } 358 359 /** 360 * Get the segment-segment intersection of two line segments 361 * @param x1 The x coordinate of the first point (first segment) 362 * @param y1 The y coordinate of the first point (first segment) 363 * @param x2 The x coordinate of the second point (first segment) 364 * @param y2 The y coordinate of the second point (first segment) 365 * @param x3 The x coordinate of the third point (second segment) 366 * @param y3 The y coordinate of the third point (second segment) 367 * @param x4 The x coordinate of the fourth point (second segment) 368 * @param y4 The y coordinate of the fourth point (second segment) 369 * @return {@code null} if no intersection was found, otherwise [x, y] 370 */ 371 private static double[] getSegmentSegmentIntersection(double x1, double y1, double x2, double y2, double x3, double y3, 372 double x4, double y4) { 373 374 //TODO: do this locally. 375 //TODO: remove this check after careful testing 376 if (!Line2D.linesIntersect(x1, y1, x2, y2, x3, y3, x4, y4)) { 377 return null; 378 } 379 380 // solve line-line intersection in parametric form: 381 // (x1,y1) + (x2-x1,y2-y1)* u = (x3,y3) + (x4-x3,y4-y3)* v 382 // (x2-x1,y2-y1)*u - (x4-x3,y4-y3)*v = (x3-x1,y3-y1) 383 // if 0<= u,v <=1, intersection exists at ( x1+ (x2-x1)*u, y1 + (y2-y1)*u ) 384 385 final double a1 = x2 - x1; 386 final double b1 = x3 - x4; 387 final double c1 = x3 - x1; 388 389 final double a2 = y2 - y1; 390 final double b2 = y3 - y4; 391 final double c2 = y3 - y1; 392 393 // Solve the equations 394 final double det = a1*b2 - a2*b1; 395 396 final double uu = b2*c1 - b1*c2; 397 final double vv = a1*c2 - a2*c1; 398 final double mag = Math.abs(uu)+Math.abs(vv); 399 400 if (Math.abs(det) > 1e-12 * mag) { 401 double u = uu/det, v = vv/det; 402 if (u > -1e-8 && u < 1+1e-8 && v > -1e-8 && v < 1+1e-8) { 403 if (u < 0) { 404 u = 0; 405 } 406 if (u > 1) { 407 u = 1.0; 408 } 409 return new double[] {x1+a1*u, y1+a2*u}; 410 } else { 411 return null; 412 } 413 } else { 414 // parallel lines 415 return null; 416 } 417 } 418 419 /** 420 * Finds the intersection of two lines of infinite length. 421 * 422 * @param p1 first point on first line 423 * @param p2 second point on first line 424 * @param p3 first point on second line 425 * @param p4 second point on second line 426 * @return EastNorth null if no intersection was found, the coordinates of the intersection otherwise 427 * @throws IllegalArgumentException if a parameter is null or without valid coordinates 428 */ 429 public static EastNorth getLineLineIntersection(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) { 430 431 CheckParameterUtil.ensureThat(p1.isValid(), () -> p1 + INVALID_COORDINATE_MSG); 432 CheckParameterUtil.ensureThat(p2.isValid(), () -> p2 + INVALID_COORDINATE_MSG); 433 CheckParameterUtil.ensureThat(p3.isValid(), () -> p3 + INVALID_COORDINATE_MSG); 434 CheckParameterUtil.ensureThat(p4.isValid(), () -> p4 + INVALID_COORDINATE_MSG); 435 436 // Basically, the formula from wikipedia is used: 437 // https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection 438 // However, large numbers lead to rounding errors (see #10286). 439 // To avoid this, p1 is first subtracted from each of the points: 440 // p1' = 0 441 // p2' = p2 - p1 442 // p3' = p3 - p1 443 // p4' = p4 - p1 444 // In the end, p1 is added to the intersection point of segment p1'/p2' 445 // and segment p3'/p4'. 446 447 // Convert line from (point, point) form to ax+by=c 448 final double a1 = p2.getY() - p1.getY(); 449 final double b1 = p1.getX() - p2.getX(); 450 451 final double a2 = p4.getY() - p3.getY(); 452 final double b2 = p3.getX() - p4.getX(); 453 454 // Solve the equations 455 final double det = a1 * b2 - a2 * b1; 456 if (det == 0) { 457 return null; // Lines are parallel 458 } 459 460 final double c2 = (p4.getX() - p1.getX()) * (p3.getY() - p1.getY()) - (p3.getX() - p1.getX()) * (p4.getY() - p1.getY()); 461 462 return new EastNorth(b1 * c2 / det + p1.getX(), -a1 * c2 / det + p1.getY()); 463 } 464 465 /** 466 * Check if the segment p1 - p2 is parallel to p3 - p4 467 * @param p1 First point for first segment 468 * @param p2 Second point for first segment 469 * @param p3 First point for second segment 470 * @param p4 Second point for second segment 471 * @return <code>true</code> if they are parallel or close to parallel 472 */ 473 public static boolean segmentsParallel(EastNorth p1, EastNorth p2, EastNorth p3, EastNorth p4) { 474 475 CheckParameterUtil.ensureThat(p1.isValid(), () -> p1 + INVALID_COORDINATE_MSG); 476 CheckParameterUtil.ensureThat(p2.isValid(), () -> p2 + INVALID_COORDINATE_MSG); 477 CheckParameterUtil.ensureThat(p3.isValid(), () -> p3 + INVALID_COORDINATE_MSG); 478 CheckParameterUtil.ensureThat(p4.isValid(), () -> p4 + INVALID_COORDINATE_MSG); 479 480 // Convert line from (point, point) form to ax+by=c 481 final double a1 = p2.getY() - p1.getY(); 482 final double b1 = p1.getX() - p2.getX(); 483 484 final double a2 = p4.getY() - p3.getY(); 485 final double b2 = p3.getX() - p4.getX(); 486 487 // Solve the equations 488 double det = a1 * b2 - a2 * b1; 489 // remove influence of of scaling factor 490 det /= Math.sqrt(a1*a1 + b1*b1) * Math.sqrt(a2*a2 + b2*b2); 491 return Math.abs(det) < 1e-3; 492 } 493 494 private static EastNorth closestPointTo(EastNorth p1, EastNorth p2, EastNorth point, boolean segmentOnly) { 495 CheckParameterUtil.ensureParameterNotNull(p1, "p1"); 496 CheckParameterUtil.ensureParameterNotNull(p2, "p2"); 497 CheckParameterUtil.ensureParameterNotNull(point, "point"); 498 499 final double ldx = p2.getX() - p1.getX(); 500 final double ldy = p2.getY() - p1.getY(); 501 502 //segment zero length 503 if (ldx == 0 && ldy == 0) { 504 return p1; 505 } 506 507 final double pdx = point.getX() - p1.getX(); 508 final double pdy = point.getY() - p1.getY(); 509 510 final double offset = (pdx * ldx + pdy * ldy) / (ldx * ldx + ldy * ldy); 511 512 if (segmentOnly && offset <= 0) { 513 return p1; 514 } else if (segmentOnly && offset >= 1) { 515 return p2; 516 } else { 517 return p1.interpolate(p2, offset); 518 } 519 } 520 521 /** 522 * Calculates closest point to a line segment. 523 * @param segmentP1 First point determining line segment 524 * @param segmentP2 Second point determining line segment 525 * @param point Point for which a closest point is searched on line segment [P1,P2] 526 * @return segmentP1 if it is the closest point, segmentP2 if it is the closest point, 527 * a new point if closest point is between segmentP1 and segmentP2. 528 * @see #closestPointToLine 529 * @since 3650 530 */ 531 public static EastNorth closestPointToSegment(EastNorth segmentP1, EastNorth segmentP2, EastNorth point) { 532 return closestPointTo(segmentP1, segmentP2, point, true); 533 } 534 535 /** 536 * Calculates closest point to a line. 537 * @param lineP1 First point determining line 538 * @param lineP2 Second point determining line 539 * @param point Point for which a closest point is searched on line (P1,P2) 540 * @return The closest point found on line. It may be outside the segment [P1,P2]. 541 * @see #closestPointToSegment 542 * @since 4134 543 */ 544 public static EastNorth closestPointToLine(EastNorth lineP1, EastNorth lineP2, EastNorth point) { 545 return closestPointTo(lineP1, lineP2, point, false); 546 } 547 548 /** 549 * This method tests if secondNode is clockwise to first node. 550 * <p> 551 * The line through the two points commonNode and firstNode divides the 552 * plane into two parts. The test returns true, if secondNode lies in 553 * the part that is to the right when traveling in the direction from 554 * commonNode to firstNode. 555 * 556 * @param commonNode starting point for both vectors 557 * @param firstNode first vector end node 558 * @param secondNode second vector end node 559 * @return true if first vector is clockwise before second vector. 560 */ 561 public static boolean angleIsClockwise(EastNorth commonNode, EastNorth firstNode, EastNorth secondNode) { 562 563 CheckParameterUtil.ensureThat(commonNode.isValid(), () -> commonNode + INVALID_COORDINATE_MSG); 564 CheckParameterUtil.ensureThat(firstNode.isValid(), () -> firstNode + INVALID_COORDINATE_MSG); 565 CheckParameterUtil.ensureThat(secondNode.isValid(), () -> secondNode + INVALID_COORDINATE_MSG); 566 567 final double dy1 = firstNode.getY() - commonNode.getY(); 568 final double dy2 = secondNode.getY() - commonNode.getY(); 569 final double dx1 = firstNode.getX() - commonNode.getX(); 570 final double dx2 = secondNode.getX() - commonNode.getX(); 571 572 return dy1 * dx2 - dx1 * dy2 > 0; 573 } 574 575 /** 576 * Returns the Area of a polygon, from its list of nodes. 577 * @param polygon List of nodes forming polygon 578 * @return Area for the given list of nodes (EastNorth coordinates) 579 * @since 6841 580 */ 581 public static Area getArea(List<? extends INode> polygon) { 582 final Path2D path = new Path2D.Double(Path2D.WIND_NON_ZERO, polygon.size()); 583 584 boolean begin = true; 585 for (INode n : polygon) { 586 final EastNorth en = n.getEastNorth(); 587 if (en != null) { 588 if (begin) { 589 path.moveTo(en.getX(), en.getY()); 590 begin = false; 591 } else { 592 path.lineTo(en.getX(), en.getY()); 593 } 594 } 595 } 596 if (!begin) { 597 path.closePath(); 598 } 599 600 return new Area(path); 601 } 602 603 /** 604 * Builds a path from a list of nodes 605 * @param polygon Nodes, forming a closed polygon 606 * @param path2d path to add to; can be null, then a new path is created 607 * @return the path (LatLon coordinates) 608 * @since 13638 (signature) 609 */ 610 public static Path2D buildPath2DLatLon(List<? extends ILatLon> polygon, Path2D path2d) { 611 final Path2D path = path2d != null ? path2d : new Path2D.Double(); 612 boolean begin = true; 613 for (ILatLon n : polygon) { 614 if (begin) { 615 path.moveTo(n.lon(), n.lat()); 616 begin = false; 617 } else { 618 path.lineTo(n.lon(), n.lat()); 619 } 620 } 621 if (!begin) { 622 path.closePath(); 623 } 624 return path; 625 } 626 627 /** 628 * Calculate area in east/north space for given primitive. Uses {@link MultipolygonCache} for multipolygon relations. 629 * @param p the primitive 630 * @return the area in east/north space, might be empty if the primitive is incomplete or not closed or a node 631 * since 15938 632 */ 633 public static Area getAreaEastNorth(IPrimitive p) { 634 if (p instanceof Way && ((Way) p).isClosed()) { 635 return Geometry.getArea(((Way) p).getNodes()); 636 } 637 if (p instanceof Relation && p.isMultipolygon() && !p.isIncomplete()) { 638 final Multipolygon mp = MultipolygonCache.getInstance().get((Relation) p); 639 if (mp.getOpenEnds().isEmpty()) { 640 final Path2D path = new Path2D.Double(); 641 path.setWindingRule(Path2D.WIND_EVEN_ODD); 642 for (PolyData pd : mp.getCombinedPolygons()) { 643 path.append(pd.get(), false); 644 } 645 return new Area(path); 646 } 647 } 648 return new Area(); 649 } 650 651 /** 652 * Returns the Area of a polygon, from the multipolygon relation. 653 * @param multipolygon the multipolygon relation 654 * @return Area for the multipolygon (LatLon coordinates) 655 */ 656 public static Area getAreaLatLon(Relation multipolygon) { 657 final Multipolygon mp = MultipolygonCache.getInstance().get(multipolygon); 658 final Path2D path = new Path2D.Double(); 659 path.setWindingRule(Path2D.WIND_EVEN_ODD); 660 for (Multipolygon.PolyData pd : mp.getCombinedPolygons()) { 661 buildPath2DLatLon(pd.getNodes(), path); 662 for (Multipolygon.PolyData pdInner : pd.getInners()) { 663 buildPath2DLatLon(pdInner.getNodes(), path); 664 } 665 } 666 return new Area(path); 667 } 668 669 /** 670 * Tests if two polygons intersect. 671 * @param first List of nodes forming first polygon 672 * @param second List of nodes forming second polygon 673 * @return intersection kind 674 */ 675 public static PolygonIntersection polygonIntersection(List<? extends INode> first, List<? extends INode> second) { 676 final Area a1 = getArea(first); 677 final Area a2 = getArea(second); 678 return polygonIntersection(a1, a2, INTERSECTION_EPS_EAST_NORTH); 679 } 680 681 /** 682 * Tests if two polygons intersect. It is assumed that the area is given in East North points. 683 * @param a1 Area of first polygon 684 * @param a2 Area of second polygon 685 * @return intersection kind 686 * @since 6841 687 */ 688 public static PolygonIntersection polygonIntersection(Area a1, Area a2) { 689 return polygonIntersection(a1, a2, INTERSECTION_EPS_EAST_NORTH); 690 } 691 692 /** 693 * Tests if two polygons intersect. 694 * @param a1 Area of first polygon 695 * @param a2 Area of second polygon 696 * @param eps an area threshold, everything below is considered an empty intersection 697 * @return intersection kind 698 */ 699 public static PolygonIntersection polygonIntersection(Area a1, Area a2, double eps) { 700 return polygonIntersectionResult(a1, a2, eps).a; 701 } 702 703 /** 704 * Calculate intersection area and kind of intersection between two polygons. 705 * @param a1 Area of first polygon 706 * @param a2 Area of second polygon 707 * @param eps an area threshold, everything below is considered an empty intersection 708 * @return pair with intersection kind and intersection area (never null, but maybe empty) 709 * @since 15938 710 */ 711 public static Pair<PolygonIntersection, Area> polygonIntersectionResult(Area a1, Area a2, double eps) { 712 // Simple intersect check (if their bounds don't intersect, don't bother going further; there will be no intersection) 713 // This avoids the more expensive Area#intersect call some of the time (decreases CPU and memory allocation by ~95%) 714 // in Mesa County, CO geometry validator test runs. 715 final Rectangle2D a12d = a1.getBounds2D(); 716 final Rectangle2D a22d = a2.getBounds2D(); 717 if (!a12d.intersects(a22d) || !a1.intersects(a22d) || !a2.intersects(a12d)) { 718 return new Pair<>(PolygonIntersection.OUTSIDE, new Area()); 719 } 720 final Area inter = new Area(a1); 721 inter.intersect(a2); 722 723 // Note: Area has an equals method that takes Area; it does _not_ override the Object.equals method. 724 if (inter.isEmpty() || !checkIntersection(inter, eps)) { 725 return new Pair<>(PolygonIntersection.OUTSIDE, inter); 726 } else if (a22d.contains(a12d) && inter.equals(a1)) { 727 return new Pair<>(PolygonIntersection.FIRST_INSIDE_SECOND, inter); 728 } else if (a12d.contains(a22d) && inter.equals(a2)) { 729 return new Pair<>(PolygonIntersection.SECOND_INSIDE_FIRST, inter); 730 } else { 731 return new Pair<>(PolygonIntersection.CROSSING, inter); 732 } 733 } 734 735 /** 736 * Check an intersection area which might describe multiple small polygons. 737 * Return true if any of the polygons is bigger than the given threshold. 738 * @param inter the intersection area 739 * @param eps an area threshold, everything below is considered an empty intersection 740 * @return true if any of the polygons is bigger than the given threshold 741 */ 742 private static boolean checkIntersection(Area inter, double eps) { 743 final PathIterator pit = inter.getPathIterator(null); 744 final double[] res = new double[6]; 745 Rectangle2D r = new Rectangle2D.Double(); 746 while (!pit.isDone()) { 747 final int type = pit.currentSegment(res); 748 switch (type) { 749 case PathIterator.SEG_MOVETO: 750 r = new Rectangle2D.Double(res[0], res[1], 0, 0); 751 break; 752 case PathIterator.SEG_LINETO: 753 r.add(res[0], res[1]); 754 break; 755 case PathIterator.SEG_CLOSE: 756 if (r.getWidth() > eps || r.getHeight() > eps) { 757 return true; 758 } 759 break; 760 default: 761 break; 762 } 763 pit.next(); 764 } 765 return false; 766 } 767 768 /** 769 * Tests if point is inside a polygon. The polygon can be self-intersecting. In such case the contains function works in xor-like manner. 770 * @param polygonNodes list of nodes from polygon path. 771 * @param point the point to test 772 * @return true if the point is inside polygon. 773 */ 774 public static boolean nodeInsidePolygon(INode point, List<? extends INode> polygonNodes) { 775 if (polygonNodes.size() < 2) { 776 return false; 777 } 778 779 //iterate each side of the polygon, start with the last segment 780 INode oldPoint = polygonNodes.get(polygonNodes.size() - 1); 781 782 if (!oldPoint.isLatLonKnown()) { 783 return false; 784 } 785 786 boolean inside = false; 787 INode p1, p2; 788 789 for (INode newPoint : polygonNodes) { 790 //skip duplicate points 791 if (newPoint.equals(oldPoint)) { 792 continue; 793 } 794 795 if (!newPoint.isLatLonKnown()) { 796 return false; 797 } 798 799 //order points so p1.lat <= p2.lat 800 if (newPoint.getEastNorth().getY() > oldPoint.getEastNorth().getY()) { 801 p1 = oldPoint; 802 p2 = newPoint; 803 } else { 804 p1 = newPoint; 805 p2 = oldPoint; 806 } 807 808 final EastNorth pEN = point.getEastNorth(); 809 final EastNorth opEN = oldPoint.getEastNorth(); 810 final EastNorth npEN = newPoint.getEastNorth(); 811 final EastNorth p1EN = p1.getEastNorth(); 812 final EastNorth p2EN = p2.getEastNorth(); 813 814 if (pEN != null && opEN != null && npEN != null && p1EN != null && p2EN != null) { 815 //test if the line is crossed and if so invert the inside flag. 816 if ((npEN.getY() < pEN.getY()) == (pEN.getY() <= opEN.getY()) 817 && (pEN.getX() - p1EN.getX()) * (p2EN.getY() - p1EN.getY()) 818 < (p2EN.getX() - p1EN.getX()) * (pEN.getY() - p1EN.getY())) { 819 inside = !inside; 820 } 821 } 822 823 oldPoint = newPoint; 824 } 825 826 return inside; 827 } 828 829 /** 830 * Returns area of a closed way in square meters. 831 * 832 * @param way Way to measure, should be closed (first node is the same as last node) 833 * @return area of the closed way. 834 */ 835 public static double closedWayArea(Way way) { 836 return getAreaAndPerimeter(way.getNodes(), Projections.getProjectionByCode("EPSG:54008")).getArea(); 837 } 838 839 /** 840 * Returns area of a multipolygon in square meters. 841 * 842 * @param multipolygon the multipolygon to measure 843 * @return area of the multipolygon. 844 */ 845 public static double multipolygonArea(Relation multipolygon) { 846 final Multipolygon mp = MultipolygonCache.getInstance().get(multipolygon); 847 return mp.getCombinedPolygons().stream() 848 .mapToDouble(pd -> pd.getAreaAndPerimeter(Projections.getProjectionByCode("EPSG:54008")).getArea()) 849 .sum(); 850 } 851 852 /** 853 * Computes the area of a closed way and multipolygon in square meters, or {@code null} for other primitives 854 * 855 * @param osm the primitive to measure 856 * @return area of the primitive, or {@code null} 857 * @since 13638 (signature) 858 */ 859 public static Double computeArea(IPrimitive osm) { 860 if (osm instanceof Way && ((Way) osm).isClosed()) { 861 return closedWayArea((Way) osm); 862 } else if (osm instanceof Relation && osm.isMultipolygon() && !((Relation) osm).hasIncompleteMembers()) { 863 return multipolygonArea((Relation) osm); 864 } else { 865 return null; 866 } 867 } 868 869 /** 870 * Determines whether a way is oriented clockwise. 871 * <p> 872 * Internals: Assuming a closed non-looping way, compute twice the area 873 * of the polygon using the formula {@code 2 * area = sum (X[n] * Y[n+1] - X[n+1] * Y[n])}. 874 * If the area is negative the way is ordered in a clockwise direction. 875 * <p> 876 * See <a href="https://web.archive.org/web/20120722100030/http://paulbourke.net/geometry/polyarea/"> 877 * https://paulbourke.net/geometry/polyarea/ 878 * </a> 879 * 880 * @param w the way to be checked. 881 * @return true if and only if way is oriented clockwise. 882 * @throws IllegalArgumentException if way is not closed (see {@link Way#isClosed}). 883 */ 884 public static boolean isClockwise(Way w) { 885 return isClockwise(w.getNodes()); 886 } 887 888 /** 889 * Determines whether path from nodes list is oriented clockwise. 890 * @param nodes Nodes list to be checked. 891 * @return true if and only if way is oriented clockwise. 892 * @throws IllegalArgumentException if way is not closed (see {@link Way#isClosed}). 893 * @see #isClockwise(Way) 894 */ 895 public static boolean isClockwise(List<? extends INode> nodes) { 896 final int nodesCount = nodes.size(); 897 if (nodesCount < 3 || nodes.get(0) != nodes.get(nodesCount - 1)) { 898 throw new IllegalArgumentException("Way must be closed to check orientation."); 899 } 900 double area2 = 0.; 901 902 for (int node = 1; node <= /*sic! consider last-first as well*/ nodesCount; node++) { 903 final INode coorPrev = nodes.get(node - 1); 904 final INode coorCurr = nodes.get(node % nodesCount); 905 area2 += coorPrev.lon() * coorCurr.lat(); 906 area2 -= coorCurr.lon() * coorPrev.lat(); 907 } 908 return area2 < 0; 909 } 910 911 /** 912 * Returns angle of a segment defined with 2 point coordinates. 913 * 914 * @param p1 first point 915 * @param p2 second point 916 * @return Angle in radians (-pi, pi] 917 */ 918 public static double getSegmentAngle(EastNorth p1, EastNorth p2) { 919 920 CheckParameterUtil.ensureThat(p1.isValid(), () -> p1 + INVALID_COORDINATE_MSG); 921 CheckParameterUtil.ensureThat(p2.isValid(), () -> p2 + INVALID_COORDINATE_MSG); 922 923 return Math.atan2(p2.north() - p1.north(), p2.east() - p1.east()); 924 } 925 926 /** 927 * Returns angle of a corner defined with 3 point coordinates. 928 * 929 * @param p1 first point 930 * @param common Common end point 931 * @param p3 third point 932 * @return Angle in radians (-pi, pi] 933 */ 934 public static double getCornerAngle(EastNorth p1, EastNorth common, EastNorth p3) { 935 936 CheckParameterUtil.ensureThat(p1.isValid(), () -> p1 + INVALID_COORDINATE_MSG); 937 CheckParameterUtil.ensureThat(common.isValid(), () -> common + INVALID_COORDINATE_MSG); 938 CheckParameterUtil.ensureThat(p3.isValid(), () -> p3 + INVALID_COORDINATE_MSG); 939 940 double result = getSegmentAngle(common, p1) - getSegmentAngle(common, p3); 941 if (result <= -Math.PI) { 942 result += 2 * Math.PI; 943 } 944 945 if (result > Math.PI) { 946 result -= 2 * Math.PI; 947 } 948 949 return result; 950 } 951 952 /** 953 * Get angles in radians and return its value in range [0, 180]. 954 * 955 * @param angle the angle in radians 956 * @return normalized angle in degrees 957 * @since 13670 958 */ 959 public static double getNormalizedAngleInDegrees(double angle) { 960 return Math.abs(180 * angle / Math.PI); 961 } 962 963 /** 964 * Compute the centroid/barycenter of nodes 965 * @param nodes Nodes for which the centroid is wanted 966 * @return the centroid of nodes 967 * @see Geometry#getCenter 968 */ 969 public static EastNorth getCentroid(List<? extends INode> nodes) { 970 return getCentroidEN(nodes.stream().filter(INode::isLatLonKnown).map(INode::getEastNorth).collect(Collectors.toList())); 971 } 972 973 /** 974 * Compute the centroid/barycenter of nodes 975 * @param nodes Coordinates for which the centroid is wanted 976 * @return the centroid of nodes 977 * @since 13712 978 */ 979 public static EastNorth getCentroidEN(List<EastNorth> nodes) { 980 981 final int size = nodes.size(); 982 if (size == 1) { 983 return nodes.get(0); 984 } else if (size == 2) { 985 return nodes.get(0).getCenter(nodes.get(1)); 986 } else if (size == 0) { 987 return null; 988 } 989 990 BigDecimal area = BigDecimal.ZERO; 991 BigDecimal north = BigDecimal.ZERO; 992 BigDecimal east = BigDecimal.ZERO; 993 994 // See https://en.wikipedia.org/wiki/Centroid#Of_a_polygon for the equation used here 995 for (int i = 0; i < size; i++) { 996 final EastNorth n0 = nodes.get(i); 997 final EastNorth n1 = nodes.get((i+1) % size); 998 999 if (n0 != null && n1 != null && n0.isValid() && n1.isValid()) { 1000 final BigDecimal x0 = BigDecimal.valueOf(n0.east()); 1001 final BigDecimal y0 = BigDecimal.valueOf(n0.north()); 1002 final BigDecimal x1 = BigDecimal.valueOf(n1.east()); 1003 final BigDecimal y1 = BigDecimal.valueOf(n1.north()); 1004 1005 final BigDecimal k = x0.multiply(y1, MathContext.DECIMAL128).subtract(y0.multiply(x1, MathContext.DECIMAL128)); 1006 1007 area = area.add(k, MathContext.DECIMAL128); 1008 east = east.add(k.multiply(x0.add(x1, MathContext.DECIMAL128), MathContext.DECIMAL128)); 1009 north = north.add(k.multiply(y0.add(y1, MathContext.DECIMAL128), MathContext.DECIMAL128)); 1010 } 1011 } 1012 1013 final BigDecimal d = new BigDecimal(3, MathContext.DECIMAL128); // 1/2 * 6 = 3 1014 area = area.multiply(d, MathContext.DECIMAL128); 1015 if (area.compareTo(BigDecimal.ZERO) != 0) { 1016 north = north.divide(area, MathContext.DECIMAL128); 1017 east = east.divide(area, MathContext.DECIMAL128); 1018 } 1019 1020 return new EastNorth(east.doubleValue(), north.doubleValue()); 1021 } 1022 1023 /** 1024 * Compute the center of the circle closest to different nodes. 1025 * <p> 1026 * Ensure exact center computation in case nodes are already aligned in circle. 1027 * This is done by least square method. 1028 * Let be a_i x + b_i y + c_i = 0 equations of bisectors of each edges. 1029 * Center must be intersection of all bisectors. 1030 * <pre> 1031 * [ a1 b1 ] [ -c1 ] 1032 * With A = [ ... ... ] and Y = [ ... ] 1033 * [ an bn ] [ -cn ] 1034 * </pre> 1035 * An approximation of center of circle is (At.A)^-1.At.Y 1036 * @param nodes Nodes parts of the circle (at least 3) 1037 * @return An approximation of the center, of null if there is no solution. 1038 * @see Geometry#getCentroid 1039 * @since 6934 1040 */ 1041 public static EastNorth getCenter(List<? extends INode> nodes) { 1042 final int nc = nodes.size(); 1043 if (nc < 3) { 1044 return null; 1045 } 1046 /* 1047 * Equation of each bisector ax + by + c = 0 1048 */ 1049 final double[] a = new double[nc]; 1050 final double[] b = new double[nc]; 1051 final double[] c = new double[nc]; 1052 // Compute equation of bisector 1053 for (int i = 0; i < nc; i++) { 1054 final EastNorth pt1 = nodes.get(i).getEastNorth(); 1055 final EastNorth pt2 = nodes.get((i+1) % nc).getEastNorth(); 1056 a[i] = pt1.east() - pt2.east(); 1057 b[i] = pt1.north() - pt2.north(); 1058 final double d = Math.sqrt(a[i]*a[i] + b[i]*b[i]); 1059 if (d == 0) { 1060 return null; 1061 } 1062 a[i] /= d; 1063 b[i] /= d; 1064 final double xC = (pt1.east() + pt2.east()) / 2; 1065 final double yC = (pt1.north() + pt2.north()) / 2; 1066 c[i] = -(a[i]*xC + b[i]*yC); 1067 } 1068 // At.A = [aij] 1069 double a11 = 0, a12 = 0, a22 = 0; 1070 // At.Y = [bi] 1071 double b1 = 0, b2 = 0; 1072 for (int i = 0; i < nc; i++) { 1073 a11 += a[i]*a[i]; 1074 a12 += a[i]*b[i]; 1075 a22 += b[i]*b[i]; 1076 b1 -= a[i]*c[i]; 1077 b2 -= b[i]*c[i]; 1078 } 1079 // (At.A)^-1 = [invij] 1080 final double det = a11*a22 - a12*a12; 1081 if (Math.abs(det) < 1e-5) { 1082 return null; 1083 } 1084 final double inv11 = a22/det; 1085 final double inv12 = -a12/det; 1086 final double inv22 = a11/det; 1087 // center (xC, yC) = (At.A)^-1.At.y 1088 final double xC = inv11*b1 + inv12*b2; 1089 final double yC = inv12*b1 + inv22*b2; 1090 return new EastNorth(xC, yC); 1091 } 1092 1093 /** 1094 * Tests if the {@code node} is inside the multipolygon {@code multiPolygon}. The nullable argument 1095 * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match. 1096 * For repeated tests against {@code multiPolygon} better use {@link Geometry#filterInsideMultipolygon}. 1097 * @param node node 1098 * @param multiPolygon multipolygon 1099 * @param isOuterWayAMatch allows to decide if the immediate {@code outer} way of the multipolygon is a match 1100 * @return {@code true} if the node is inside the multipolygon 1101 */ 1102 public static boolean isNodeInsideMultiPolygon(INode node, Relation multiPolygon, Predicate<Way> isOuterWayAMatch) { 1103 return isPolygonInsideMultiPolygon(Collections.singletonList(node), multiPolygon, isOuterWayAMatch); 1104 } 1105 1106 /** 1107 * Tests if the polygon formed by {@code nodes} is inside the multipolygon {@code multiPolygon}. The nullable argument 1108 * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match. 1109 * For repeated tests against {@code multiPolygon} better use {@link Geometry#filterInsideMultipolygon}. 1110 * <p> 1111 * If {@code nodes} contains exactly one element, then it is checked whether that one node is inside the multipolygon. 1112 * @param nodes nodes forming the polygon 1113 * @param multiPolygon multipolygon 1114 * @param isOuterWayAMatch allows to decide if the immediate {@code outer} way of the multipolygon is a match 1115 * @return {@code true} if the multipolygon is valid and the polygon formed by nodes is inside the multipolygon 1116 */ 1117 public static boolean isPolygonInsideMultiPolygon(List<? extends INode> nodes, Relation multiPolygon, Predicate<Way> isOuterWayAMatch) { 1118 try { 1119 return isPolygonInsideMultiPolygon(nodes, MultipolygonBuilder.joinWays(multiPolygon), isOuterWayAMatch); 1120 } catch (MultipolygonBuilder.JoinedPolygonCreationException ex) { 1121 Logging.trace(ex); 1122 Logging.debug("Invalid multipolygon " + multiPolygon); 1123 return false; 1124 } 1125 } 1126 1127 /** 1128 * Tests if the polygon formed by {@code nodes} is inside the multipolygon {@code multiPolygon}. The nullable argument 1129 * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match. 1130 * For repeated tests against {@code multiPolygon} better use {@link Geometry#filterInsideMultipolygon}. 1131 * <p> 1132 * If {@code nodes} contains exactly one element, then it is checked whether that one node is inside the multipolygon. 1133 * @param nodes nodes forming the polygon 1134 * @param outerInner result of {@link MultipolygonBuilder#joinWays(Relation)} 1135 * @param isOuterWayAMatch allows to decide if the immediate {@code outer} way of the multipolygon is a match 1136 * @return {@code true} if the multipolygon is valid and the polygon formed by nodes is inside the multipolygon 1137 * @since 15069 1138 */ 1139 public static boolean isPolygonInsideMultiPolygon(List<? extends INode> nodes, Pair<List<JoinedPolygon>, 1140 List<JoinedPolygon>> outerInner, Predicate<Way> isOuterWayAMatch) { 1141 final Area a1 = nodes.size() == 1 ? null : getArea(nodes); 1142 // Test if object is inside an outer member 1143 for (JoinedPolygon out : outerInner.a) { 1144 if (a1 == null 1145 ? nodeInsidePolygon(nodes.get(0), out.nodes) 1146 : PolygonIntersection.FIRST_INSIDE_SECOND == polygonIntersection(a1, out.area)) { 1147 // If inside an outer, check it is not inside an inner 1148 final boolean insideInner = outerInner.b.stream().anyMatch(in -> a1 == null 1149 ? nodeInsidePolygon(nodes.get(0), in.nodes) 1150 : in.area.getBounds2D().contains(a1.getBounds2D()) 1151 && polygonIntersection(a1, in.area) == PolygonIntersection.FIRST_INSIDE_SECOND 1152 && polygonIntersection(in.area, out.area) == PolygonIntersection.FIRST_INSIDE_SECOND); 1153 if (!insideInner) { 1154 // Final check using predicate 1155 if (isOuterWayAMatch == null || isOuterWayAMatch.test(out.ways.get(0) 1156 /* TODO give a better representation of the outer ring to the predicate */)) { 1157 return true; 1158 } 1159 } 1160 } 1161 } 1162 return false; 1163 } 1164 1165 /** 1166 * Find all primitives in the given collection which are inside the given polygon. 1167 * 1168 * @param primitives the primitives 1169 * @param polygon the closed way or multipolygon relation 1170 * @return a new list containing the found primitives, empty if polygon is invalid or nothing was found. 1171 * @see Geometry#filterInsidePolygon 1172 * @see Geometry#filterInsideMultipolygon 1173 * @since 15730 1174 */ 1175 public static List<IPrimitive> filterInsideAnyPolygon(Collection<IPrimitive> primitives, IPrimitive polygon) { 1176 if (polygon instanceof IWay<?>) { 1177 return filterInsidePolygon(primitives, (IWay<?>) polygon); 1178 } else if (polygon instanceof Relation && polygon.isMultipolygon()) { 1179 return filterInsideMultipolygon(primitives, (Relation) polygon); 1180 } 1181 return Collections.emptyList(); 1182 } 1183 1184 /** 1185 * Find all primitives in the given collection which are inside the given polygon. 1186 * Unclosed ways and multipolygon relations with unclosed outer rings are ignored. 1187 * 1188 * @param primitives the primitives 1189 * @param polygon the polygon 1190 * @return a new list containing the found primitives, empty if polygon is invalid or nothing was found. 1191 * @since 15069 (for {@link List} of {@code primitives}, 15730 for a {@link Collection} of {@code primitives}) 1192 */ 1193 public static List<IPrimitive> filterInsidePolygon(Collection<IPrimitive> primitives, IWay<?> polygon) { 1194 final List<IPrimitive> res = new ArrayList<>(); 1195 if (!polygon.isClosed() || polygon.getNodesCount() <= 3) { 1196 return res; 1197 } 1198 /* polygon area in east north space, calculated only when really needed */ 1199 Area polygonArea = null; 1200 for (IPrimitive p : primitives) { 1201 if (p instanceof INode) { 1202 if (nodeInsidePolygon((INode) p, polygon.getNodes())) { 1203 res.add(p); 1204 } 1205 } else if (p instanceof IWay) { 1206 if (((IWay<?>) p).isClosed()) { 1207 if (polygonArea == null) { 1208 polygonArea = getArea(polygon.getNodes()); 1209 } 1210 if (PolygonIntersection.FIRST_INSIDE_SECOND == polygonIntersection(getArea(((IWay<?>) p).getNodes()), 1211 polygonArea)) { 1212 res.add(p); 1213 } 1214 } 1215 } else if (p.isMultipolygon()) { 1216 if (polygonArea == null) { 1217 polygonArea = getArea(polygon.getNodes()); 1218 } 1219 final Multipolygon mp = p.getDataSet() != null ? MultipolygonCache.getInstance().get((Relation) p) 1220 : new Multipolygon((Relation) p); 1221 boolean inside = true; 1222 // a (valid) multipolygon is inside the polygon if all outer rings are inside 1223 for (PolyData outer : mp.getOuterPolygons()) { 1224 if (!outer.isClosed() 1225 || !polygonArea.getBounds2D().contains(outer.getBounds()) 1226 || PolygonIntersection.FIRST_INSIDE_SECOND != polygonIntersection(getArea(outer.getNodes()), 1227 polygonArea)) { 1228 inside = false; 1229 break; 1230 } 1231 } 1232 if (inside) { 1233 res.add(p); 1234 } 1235 } 1236 } 1237 return res; 1238 } 1239 1240 /** 1241 * Find all primitives in the given collection which are inside the given multipolygon. Members of the multipolygon are 1242 * ignored. Unclosed ways and multipolygon relations with unclosed outer rings are ignored. 1243 * @param primitives the primitives 1244 * @param multiPolygon the multipolygon relation 1245 * @return a new list containing the found primitives, empty if multipolygon is invalid or nothing was found. 1246 * @since 15069 1247 */ 1248 public static List<IPrimitive> filterInsideMultipolygon(Collection<IPrimitive> primitives, Relation multiPolygon) { 1249 return filterInsideMultipolygon(primitives, multiPolygon, null); 1250 } 1251 1252 /** 1253 * Find all primitives in the given collection which are inside the given multipolygon. Members of the multipolygon are 1254 * ignored. Unclosed ways and multipolygon relations with unclosed outer rings are ignored. 1255 * @param primitives the primitives 1256 * @param multiPolygon the multipolygon relation 1257 * @param cache The cache to avoid calculating joined inner/outer ways multiple times (see {@link MultipolygonBuilder#joinWays(Relation)}) 1258 * @return a new list containing the found primitives, empty if multipolygon is invalid or nothing was found. 1259 * @since 19336 1260 */ 1261 public static List<IPrimitive> filterInsideMultipolygon(Collection<IPrimitive> primitives, Relation multiPolygon, 1262 Map<IRelation<?>, Pair<List<JoinedPolygon>, List<JoinedPolygon>>> cache) { 1263 final List<IPrimitive> res = new ArrayList<>(); 1264 if (primitives.isEmpty()) { 1265 return res; 1266 } 1267 1268 final Pair<List<JoinedPolygon>, List<JoinedPolygon>> outerInner; 1269 try { 1270 outerInner = MultipolygonBuilder.joinWays(cache, multiPolygon); 1271 } catch (MultipolygonBuilder.JoinedPolygonCreationException ex) { 1272 Logging.trace(ex); 1273 Logging.debug("Invalid multipolygon " + multiPolygon); 1274 return res; 1275 } 1276 1277 final Set<OsmPrimitive> members = multiPolygon.getMemberPrimitives(); 1278 for (IPrimitive p : primitives) { 1279 if (members.contains(p)) { 1280 continue; 1281 } 1282 if (p instanceof Node) { 1283 if (isPolygonInsideMultiPolygon(Collections.singletonList((Node) p), outerInner, null)) { 1284 res.add(p); 1285 } 1286 } else if (p instanceof Way) { 1287 if (((IWay<?>) p).isClosed() && isPolygonInsideMultiPolygon(((Way) p).getNodes(), outerInner, null)) { 1288 res.add(p); 1289 } 1290 } else if (p.isMultipolygon()) { 1291 final Multipolygon mp = new Multipolygon((Relation) p); 1292 // a (valid) multipolygon is inside multiPolygon if all outer rings are inside 1293 final boolean inside = mp.getOuterPolygons().stream() 1294 .allMatch(outer -> outer.isClosed() && isPolygonInsideMultiPolygon(outer.getNodes(), outerInner, null)); 1295 if (inside) { 1296 res.add(p); 1297 } 1298 } 1299 } 1300 return res; 1301 } 1302 1303 /** 1304 * Data class to hold two double values (area and perimeter of a polygon). 1305 */ 1306 public static class AreaAndPerimeter { 1307 private final double area; 1308 private final double perimeter; 1309 1310 /** 1311 * Create a new {@link AreaAndPerimeter} 1312 * @param area The area 1313 * @param perimeter The perimeter 1314 */ 1315 public AreaAndPerimeter(double area, double perimeter) { 1316 this.area = area; 1317 this.perimeter = perimeter; 1318 } 1319 1320 /** 1321 * Gets the area 1322 * @return The area size 1323 */ 1324 public double getArea() { 1325 return area; 1326 } 1327 1328 /** 1329 * Gets the perimeter 1330 * @return The perimeter length 1331 */ 1332 public double getPerimeter() { 1333 return perimeter; 1334 } 1335 } 1336 1337 /** 1338 * Calculate area and perimeter length of a polygon. 1339 * <p> 1340 * Uses current projection; units are that of the projected coordinates. 1341 * 1342 * @param nodes the list of nodes representing the polygon 1343 * @return area and perimeter 1344 */ 1345 public static AreaAndPerimeter getAreaAndPerimeter(List<? extends ILatLon> nodes) { 1346 return getAreaAndPerimeter(nodes, null); 1347 } 1348 1349 /** 1350 * Calculate area and perimeter length of a polygon in the given projection. 1351 * 1352 * @param nodes the list of nodes representing the polygon 1353 * @param projection the projection to use for the calculation, {@code null} defaults to {@link ProjectionRegistry#getProjection()} 1354 * @return area and perimeter 1355 * @since 13638 (signature) 1356 */ 1357 public static AreaAndPerimeter getAreaAndPerimeter(List<? extends ILatLon> nodes, Projection projection) { 1358 CheckParameterUtil.ensureParameterNotNull(nodes, "nodes"); 1359 double area = 0; 1360 double perimeter = 0; 1361 final Projection useProjection = projection == null ? ProjectionRegistry.getProjection() : projection; 1362 1363 if (!nodes.isEmpty()) { 1364 final boolean closed = nodes.get(0) == nodes.get(nodes.size() - 1); 1365 final int numSegments = closed ? nodes.size() - 1 : nodes.size(); 1366 EastNorth p1 = nodes.get(0).getEastNorth(useProjection); 1367 for (int i = 1; i <= numSegments; i++) { 1368 final ILatLon node = nodes.get(i == numSegments ? 0 : i); 1369 final EastNorth p2 = node.getEastNorth(useProjection); 1370 if (p1 != null && p2 != null) { 1371 area += p1.east() * p2.north() - p2.east() * p1.north(); 1372 perimeter += p1.distance(p2); 1373 } 1374 p1 = p2; 1375 } 1376 } 1377 return new AreaAndPerimeter(Math.abs(area) / 2, perimeter); 1378 } 1379 1380 /** 1381 * Get the closest primitive to {@code osm} from the collection of 1382 * OsmPrimitive {@code primitives} 1383 * <p> 1384 * The {@code primitives} should be fully downloaded to ensure accuracy. 1385 * <p> 1386 * Note: The complexity of this method is O(n*m), where n is the number of 1387 * children {@code osm} has plus 1, m is the number of children the 1388 * collection of primitives have plus the number of primitives in the 1389 * collection. 1390 * 1391 * @param <T> The return type of the primitive 1392 * @param osm The primitive to get the distances from 1393 * @param primitives The collection of primitives to get the distance to 1394 * @return The closest {@link OsmPrimitive}. This is not determinative. 1395 * To get all primitives that share the same distance, use 1396 * {@link Geometry#getClosestPrimitives}. 1397 * @since 15035 1398 */ 1399 public static <T extends OsmPrimitive> T getClosestPrimitive(OsmPrimitive osm, Collection<T> primitives) { 1400 final Collection<T> collection = getClosestPrimitives(osm, primitives); 1401 return collection.iterator().next(); 1402 } 1403 1404 /** 1405 * Get the closest primitives to {@code osm} from the collection of 1406 * OsmPrimitive {@code primitives} 1407 * <p> 1408 * The {@code primitives} should be fully downloaded to ensure accuracy. 1409 * <p> 1410 * Note: The complexity of this method is O(n*m), where n is the number of 1411 * children {@code osm} has plus 1, m is the number of children the 1412 * collection of primitives have plus the number of primitives in the 1413 * collection. 1414 * 1415 * @param <T> The return type of the primitive 1416 * @param osm The primitive to get the distances from 1417 * @param primitives The collection of primitives to get the distance to 1418 * @return The closest {@link OsmPrimitive}s. May be empty. 1419 * @since 15035 1420 */ 1421 public static <T extends OsmPrimitive> Collection<T> getClosestPrimitives(OsmPrimitive osm, Collection<T> primitives) { 1422 double lowestDistance = Double.MAX_VALUE; 1423 final TreeSet<T> closest = new TreeSet<>(); 1424 for (T primitive : primitives) { 1425 final double distance = getDistance(osm, primitive); 1426 if (Double.isNaN(distance)) { 1427 continue; 1428 } 1429 final int comp = Double.compare(distance, lowestDistance); 1430 if (comp < 0) { 1431 closest.clear(); 1432 lowestDistance = distance; 1433 closest.add(primitive); 1434 } else if (comp == 0) { 1435 closest.add(primitive); 1436 } 1437 } 1438 return closest; 1439 } 1440 1441 /** 1442 * Get the furthest primitive to {@code osm} from the collection of 1443 * OsmPrimitive {@code primitives} 1444 * <p> 1445 * The {@code primitives} should be fully downloaded to ensure accuracy. 1446 * <p> 1447 * It does NOT give the furthest primitive based off of the furthest 1448 * part of that primitive 1449 * <p> 1450 * Note: The complexity of this method is O(n*m), where n is the number of 1451 * children {@code osm} has plus 1, m is the number of children the 1452 * collection of primitives have plus the number of primitives in the 1453 * collection. 1454 * 1455 * @param <T> The return type of the primitive 1456 * @param osm The primitive to get the distances from 1457 * @param primitives The collection of primitives to get the distance to 1458 * @return The furthest {@link OsmPrimitive}. This is not determinative. 1459 * To get all primitives that share the same distance, use 1460 * {@link Geometry#getFurthestPrimitives} 1461 * @since 15035 1462 */ 1463 public static <T extends OsmPrimitive> T getFurthestPrimitive(OsmPrimitive osm, Collection<T> primitives) { 1464 return getFurthestPrimitives(osm, primitives).iterator().next(); 1465 } 1466 1467 /** 1468 * Get the furthest primitives to {@code osm} from the collection of 1469 * OsmPrimitive {@code primitives} 1470 * <p> 1471 * The {@code primitives} should be fully downloaded to ensure accuracy. 1472 * <p> 1473 * It does NOT give the furthest primitive based off of the furthest 1474 * part of that primitive 1475 * <p> 1476 * Note: The complexity of this method is O(n*m), where n is the number of 1477 * children {@code osm} has plus 1, m is the number of children the 1478 * collection of primitives have plus the number of primitives in the 1479 * collection. 1480 * 1481 * @param <T> The return type of the primitive 1482 * @param osm The primitive to get the distances from 1483 * @param primitives The collection of primitives to get the distance to 1484 * @return The furthest {@link OsmPrimitive}s. It may return an empty collection. 1485 * @since 15035 1486 */ 1487 public static <T extends OsmPrimitive> Collection<T> getFurthestPrimitives(OsmPrimitive osm, Collection<T> primitives) { 1488 double furthestDistance = Double.NEGATIVE_INFINITY; 1489 final TreeSet<T> furthest = new TreeSet<>(); 1490 for (T primitive : primitives) { 1491 final double distance = getDistance(osm, primitive); 1492 if (Double.isNaN(distance)) { 1493 continue; 1494 } 1495 final int comp = Double.compare(distance, furthestDistance); 1496 if (comp > 0) { 1497 furthest.clear(); 1498 furthestDistance = distance; 1499 furthest.add(primitive); 1500 } else if (comp == 0) { 1501 furthest.add(primitive); 1502 } 1503 } 1504 return furthest; 1505 } 1506 1507 /** 1508 * Get the distance between different {@link OsmPrimitive}s 1509 * @param one The primitive to get the distance from 1510 * @param two The primitive to get the distance to 1511 * @return The distance between the primitives in meters 1512 * (or the unit of the current projection, see {@link Projection}). 1513 * May return {@link Double#NaN} if one of the primitives is incomplete. 1514 * <p> 1515 * Note: The complexity is O(n*m), where (n,m) are the number of child 1516 * objects the {@link OsmPrimitive}s have. 1517 * @since 15035 1518 */ 1519 public static double getDistance(OsmPrimitive one, OsmPrimitive two) { 1520 double rValue = Double.MAX_VALUE; 1521 if (one == null || two == null || one.isIncomplete() 1522 || two.isIncomplete()) { 1523 return Double.NaN; 1524 } 1525 if (one instanceof ILatLon && two instanceof ILatLon) { 1526 rValue = ((ILatLon) one).greatCircleDistance(((ILatLon) two)); 1527 } else if (one instanceof Node && two instanceof Way) { 1528 rValue = getDistanceWayNode((Way) two, (Node) one); 1529 } else if (one instanceof Way && two instanceof Node) { 1530 rValue = getDistanceWayNode((Way) one, (Node) two); 1531 } else if (one instanceof Way && two instanceof Way) { 1532 rValue = getDistanceWayWay((Way) one, (Way) two); 1533 } else if (one instanceof Relation && !(two instanceof Relation)) { 1534 for (OsmPrimitive osmPrimitive: ((Relation) one).getMemberPrimitives()) { 1535 final double currentDistance = getDistance(osmPrimitive, two); 1536 if (currentDistance < rValue) { 1537 rValue = currentDistance; 1538 } 1539 } 1540 } else if (!(one instanceof Relation) && two instanceof Relation) { 1541 rValue = getDistance(two, one); 1542 } else if (one instanceof Relation && two instanceof Relation) { 1543 for (OsmPrimitive osmPrimitive1 : ((Relation) one).getMemberPrimitives()) { 1544 for (OsmPrimitive osmPrimitive2 : ((Relation) two).getMemberPrimitives()) { 1545 final double currentDistance = getDistance(osmPrimitive1, osmPrimitive2); 1546 if (currentDistance < rValue) { 1547 rValue = currentDistance; 1548 } 1549 } 1550 } 1551 } 1552 return rValue != Double.MAX_VALUE ? rValue : Double.NaN; 1553 } 1554 1555 /** 1556 * Get the distance between a way and a node 1557 * @param way The way to get the distance from 1558 * @param node The node to get the distance to 1559 * @return The distance between the {@code way} and the {@code node} in 1560 * meters (or the unit of the current projection, see {@link Projection}). 1561 * May return {@link Double#NaN} if the primitives are incomplete. 1562 * @since 15035 1563 */ 1564 public static double getDistanceWayNode(Way way, Node node) { 1565 if (way == null || node == null || way.getNodesCount() < 2 || !node.isLatLonKnown()) { 1566 return Double.NaN; 1567 } 1568 1569 double smallest = Double.MAX_VALUE; 1570 final EastNorth en0 = node.getEastNorth(); 1571 // go through the nodes as if they were paired 1572 final Iterator<Node> iter = way.getNodes().iterator(); 1573 EastNorth en1 = iter.next().getEastNorth(); 1574 while (iter.hasNext()) { 1575 final EastNorth en2 = iter.next().getEastNorth(); 1576 final double distance = getSegmentNodeDistSq(en1, en2, en0); 1577 if (distance < smallest) { 1578 smallest = distance; 1579 } 1580 en1 = en2; 1581 } 1582 return smallest != Double.MAX_VALUE ? Math.sqrt(smallest) : Double.NaN; 1583 } 1584 1585 /** 1586 * Get the closest {@link WaySegment} from a way to a primitive. 1587 * @param way The {@link Way} to get the distance from and the {@link WaySegment} 1588 * @param primitive The {@link OsmPrimitive} to get the distance to 1589 * @return The {@link WaySegment} that is closest to {@code primitive} from {@code way}. 1590 * If there are multiple {@link WaySegment}s with the same distance, the last 1591 * {@link WaySegment} with the same distance will be returned. 1592 * May return {@code null} if the way has fewer than two nodes or one 1593 * of the primitives is incomplete. 1594 * @since 15035 1595 */ 1596 public static WaySegment getClosestWaySegment(Way way, OsmPrimitive primitive) { 1597 if (way == null || primitive == null || way.isIncomplete() 1598 || primitive.isIncomplete()) { 1599 return null; 1600 } 1601 double lowestDistance = Double.MAX_VALUE; 1602 Pair<Node, Node> closestNodes = null; 1603 for (Pair<Node, Node> nodes : way.getNodePairs(false)) { 1604 final Way tWay = new Way(); 1605 tWay.addNode(new Node(nodes.a)); 1606 tWay.addNode(new Node(nodes.b)); 1607 final double distance = getDistance(tWay, primitive); 1608 if (distance < lowestDistance) { 1609 lowestDistance = distance; 1610 closestNodes = nodes; 1611 } 1612 } 1613 if (closestNodes == null) { 1614 return null; 1615 } 1616 return lowestDistance != Double.MAX_VALUE ? WaySegment.forNodePair(way, closestNodes.a, closestNodes.b) : null; 1617 } 1618 1619 /** 1620 * Get the distance between different ways. Iterates over the nodes of the ways, complexity is O(n*m) 1621 * (n,m giving the number of nodes) 1622 * @param w1 The first {@link Way} 1623 * @param w2 The second {@link Way} 1624 * @return The shortest distance between the ways in meters 1625 * (or the unit of the current projection, see {@link Projection}). 1626 * May return {@link Double#NaN}. 1627 * @since 15035 1628 */ 1629 public static double getDistanceWayWay(Way w1, Way w2) { 1630 if (w1 == null || w2 == null || w1.getNodesCount() < 2 || w2.getNodesCount() < 2) { 1631 return Double.NaN; 1632 } 1633 double rValue = Double.MAX_VALUE; 1634 final Iterator<Node> iter1 = w1.getNodes().iterator(); 1635 final List<Node> w2Nodes = w2.getNodes(); 1636 Node w1N1 = iter1.next(); 1637 while (iter1.hasNext()) { 1638 final Node w1N2 = iter1.next(); 1639 final Iterator<Node> iter2 = w2Nodes.iterator(); 1640 Node w2N1 = iter2.next(); 1641 while (iter2.hasNext()) { 1642 final Node w2N2 = iter2.next(); 1643 final double distance = getDistanceSegmentSegment(w1N1, w1N2, w2N1, w2N2); 1644 if (distance < rValue) { 1645 rValue = distance; 1646 } 1647 w2N1 = w2N2; 1648 } 1649 w1N1 = w1N2; 1650 } 1651 return rValue != Double.MAX_VALUE ? rValue : Double.NaN; 1652 } 1653 1654 /** 1655 * Get the distance between different {@link WaySegment}s 1656 * @param ws1 A {@link WaySegment} 1657 * @param ws2 A {@link WaySegment} 1658 * @return The distance between the two {@link WaySegment}s in meters 1659 * (or the unit of the current projection, see {@link Projection}). 1660 * May return {@link Double#NaN}. 1661 * @since 15035 1662 */ 1663 public static double getDistanceSegmentSegment(WaySegment ws1, WaySegment ws2) { 1664 return getDistanceSegmentSegment(ws1.getFirstNode(), ws1.getSecondNode(), ws2.getFirstNode(), ws2.getSecondNode()); 1665 } 1666 1667 /** 1668 * Get the distance between different {@link WaySegment}s 1669 * @param ws1Node1 The first node of the first WaySegment 1670 * @param ws1Node2 The second node of the second WaySegment 1671 * @param ws2Node1 The first node of the second WaySegment 1672 * @param ws2Node2 The second node of the second WaySegment 1673 * @return The distance between the two {@link WaySegment}s in meters 1674 * (or the unit of the current projection, see {@link Projection}). 1675 * May return {@link Double#NaN}. 1676 * @since 15035 1677 */ 1678 public static double getDistanceSegmentSegment(Node ws1Node1, Node ws1Node2, Node ws2Node1, Node ws2Node2) { 1679 if (!ws1Node1.isLatLonKnown() || !ws1Node2.isLatLonKnown() || !ws2Node1.isLatLonKnown() || !ws2Node2.isLatLonKnown()) { 1680 return Double.NaN; 1681 } 1682 final EastNorth enWs1Node1 = ws1Node1.getEastNorth(); 1683 final EastNorth enWs1Node2 = ws1Node2.getEastNorth(); 1684 final EastNorth enWs2Node1 = ws2Node1.getEastNorth(); 1685 final EastNorth enWs2Node2 = ws2Node2.getEastNorth(); 1686 if (getSegmentSegmentIntersection(enWs1Node1, enWs1Node2, enWs2Node1, enWs2Node2) != null) { 1687 return 0; 1688 } 1689 1690 final double dist1sq = getSegmentNodeDistSq(enWs1Node1, enWs1Node2, enWs2Node1); 1691 final double dist2sq = getSegmentNodeDistSq(enWs1Node1, enWs1Node2, enWs2Node2); 1692 final double dist3sq = getSegmentNodeDistSq(enWs2Node1, enWs2Node2, enWs1Node1); 1693 final double dist4sq = getSegmentNodeDistSq(enWs2Node1, enWs2Node2, enWs1Node2); 1694 final double smallest = Math.min(Math.min(dist1sq, dist2sq), Math.min(dist3sq, dist4sq)); 1695 return smallest != Double.MAX_VALUE ? Math.sqrt(smallest) : Double.NaN; 1696 } 1697 1698 /** 1699 * Create a new LatLon at a specified distance. Currently uses WGS84, but may change randomly in the future. 1700 * This does not currently attempt to be hugely accurate. The actual location may be off 1701 * depending upon the distance and the elevation, but should be within 0.0002 meters. 1702 * 1703 * @param original The originating point 1704 * @param angle The angle (from true north) in radians 1705 * @param offset The distance to the new point in the current projection's units 1706 * @return The location at the specified angle and distance from the originating point 1707 * @since 18109 1708 */ 1709 public static ILatLon getLatLonFrom(final ILatLon original, final double angle, final double offset) { 1710 final double meterOffset = ProjectionRegistry.getProjection().getMetersPerUnit() * offset; 1711 final double radianLat = Math.toRadians(original.lat()); 1712 final double radianLon = Math.toRadians(original.lon()); 1713 final double angularDistance = meterOffset / WGS84.a; 1714 final double lat = Math.asin(Math.sin(radianLat) * Math.cos(angularDistance) 1715 + Math.cos(radianLat) * Math.sin(angularDistance) * Math.cos(angle)); 1716 final double lon = radianLon + Math.atan2(Math.sin(angle) * Math.sin(angularDistance) * Math.cos(radianLat), 1717 Math.cos(angularDistance) - Math.sin(radianLat) * Math.sin(lat)); 1718 return new LatLon(Math.toDegrees(lat), Math.toDegrees(lon)); 1719 } 1720 1721 /** 1722 * Calculate closest distance between a line segment s1-s2 and a point p 1723 * @param s1 start of segment 1724 * @param s2 end of segment 1725 * @param p the point 1726 * @return the square of the euclidean distance from p to the closest point on the segment 1727 */ 1728 private static double getSegmentNodeDistSq(EastNorth s1, EastNorth s2, EastNorth p) { 1729 final EastNorth c1 = closestPointTo(s1, s2, p, true); 1730 return c1.distanceSq(p); 1731 } 1732}