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

Last change on this file since 9185 was 9108, checked in by Don-vip, 8 years ago

checkstyle

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