source: josm/trunk/src/org/openstreetmap/josm/tools/Geometry.java@ 8308

Last change on this file since 8308 was 8303, checked in by Balaitous, 9 years ago

fix #7421 - Circle created from way heads always clockwise

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