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

Last change on this file since 7022 was 7012, checked in by Don-vip, 10 years ago

see #8465 - use String switch/case where applicable

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