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

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

see #9680 - Boost multipolygon computation performance by caching Areas

  • Property svn:eol-style set to native
File size: 31.6 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<Node>();
69
70 //copy node arrays for local usage.
71 for (int pos = 0; pos < n; pos ++) {
72 newNodes[pos] = new ArrayList<Node>(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 if (begin) {
455 path.moveTo(n.getEastNorth().getX(), n.getEastNorth().getY());
456 begin = false;
457 } else {
458 path.lineTo(n.getEastNorth().getX(), n.getEastNorth().getY());
459 }
460 }
461 if (!begin) {
462 path.closePath();
463 }
464
465 return new Area(path);
466 }
467
468 /**
469 * Tests if two polygons intersect.
470 * @param first List of nodes forming first polygon
471 * @param second List of nodes forming second polygon
472 * @return intersection kind
473 */
474 public static PolygonIntersection polygonIntersection(List<Node> first, List<Node> second) {
475 Area a1 = getArea(first);
476 Area a2 = getArea(second);
477 return polygonIntersection(a1, a2);
478 }
479
480 /**
481 * Tests if two polygons intersect.
482 * @param a1 Area of first polygon
483 * @param a2 Area of second polygon
484 * @return intersection kind
485 * @since 6841
486 */
487 public static PolygonIntersection polygonIntersection(Area a1, Area a2) {
488
489 Area inter = new Area(a1);
490 inter.intersect(a2);
491
492 Rectangle bounds = inter.getBounds();
493
494 if (inter.isEmpty() || bounds.getHeight()*bounds.getWidth() <= 1.0) {
495 return PolygonIntersection.OUTSIDE;
496 } else if (inter.equals(a1)) {
497 return PolygonIntersection.FIRST_INSIDE_SECOND;
498 } else if (inter.equals(a2)) {
499 return PolygonIntersection.SECOND_INSIDE_FIRST;
500 } else {
501 return PolygonIntersection.CROSSING;
502 }
503 }
504
505 /**
506 * Tests if point is inside a polygon. The polygon can be self-intersecting. In such case the contains function works in xor-like manner.
507 * @param polygonNodes list of nodes from polygon path.
508 * @param point the point to test
509 * @return true if the point is inside polygon.
510 */
511 public static boolean nodeInsidePolygon(Node point, List<Node> polygonNodes) {
512 if (polygonNodes.size() < 2)
513 return false;
514
515 boolean inside = false;
516 Node p1, p2;
517
518 //iterate each side of the polygon, start with the last segment
519 Node oldPoint = polygonNodes.get(polygonNodes.size() - 1);
520
521 for (Node newPoint : polygonNodes) {
522 //skip duplicate points
523 if (newPoint.equals(oldPoint)) {
524 continue;
525 }
526
527 //order points so p1.lat <= p2.lat
528 if (newPoint.getEastNorth().getY() > oldPoint.getEastNorth().getY()) {
529 p1 = oldPoint;
530 p2 = newPoint;
531 } else {
532 p1 = newPoint;
533 p2 = oldPoint;
534 }
535
536 //test if the line is crossed and if so invert the inside flag.
537 if ((newPoint.getEastNorth().getY() < point.getEastNorth().getY()) == (point.getEastNorth().getY() <= oldPoint.getEastNorth().getY())
538 && (point.getEastNorth().getX() - p1.getEastNorth().getX()) * (p2.getEastNorth().getY() - p1.getEastNorth().getY())
539 < (p2.getEastNorth().getX() - p1.getEastNorth().getX()) * (point.getEastNorth().getY() - p1.getEastNorth().getY()))
540 {
541 inside = !inside;
542 }
543
544 oldPoint = newPoint;
545 }
546
547 return inside;
548 }
549
550 /**
551 * Returns area of a closed way in square meters.
552 * (approximate(?), but should be OK for small areas)
553 *
554 * Relies on the current projection: Works correctly, when
555 * one unit in projected coordinates corresponds to one meter.
556 * This is true for most projections, but not for WGS84 and
557 * Mercator (EPSG:3857).
558 *
559 * @param way Way to measure, should be closed (first node is the same as last node)
560 * @return area of the closed way.
561 */
562 public static double closedWayArea(Way way) {
563
564 //http://local.wasp.uwa.edu.au/~pbourke/geometry/polyarea/
565 double area = 0;
566 Node lastN = null;
567 for (Node n : way.getNodes()) {
568 if (lastN != null) {
569 n.getEastNorth().getX();
570
571 area += (calcX(n) * calcY(lastN)) - (calcY(n) * calcX(lastN));
572 }
573 lastN = n;
574 }
575 return Math.abs(area/2);
576 }
577
578 protected static double calcX(Node p1){
579 double lat1, lon1, lat2, lon2;
580 double dlon, dlat;
581
582 lat1 = p1.getCoor().lat() * Math.PI / 180.0;
583 lon1 = p1.getCoor().lon() * Math.PI / 180.0;
584 lat2 = lat1;
585 lon2 = 0;
586
587 dlon = lon2 - lon1;
588 dlat = lat2 - lat1;
589
590 double a = (Math.pow(Math.sin(dlat/2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon/2), 2));
591 double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
592 return 6367000 * c;
593 }
594
595 protected static double calcY(Node p1){
596 double lat1, lon1, lat2, lon2;
597 double dlon, dlat;
598
599 lat1 = p1.getCoor().lat() * Math.PI / 180.0;
600 lon1 = p1.getCoor().lon() * Math.PI / 180.0;
601 lat2 = 0;
602 lon2 = lon1;
603
604 dlon = lon2 - lon1;
605 dlat = lat2 - lat1;
606
607 double a = (Math.pow(Math.sin(dlat/2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon/2), 2));
608 double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
609 return 6367000 * c;
610 }
611
612 /**
613 * Determines whether a way is oriented clockwise.
614 *
615 * Internals: Assuming a closed non-looping way, compute twice the area
616 * of the polygon using the formula {@code 2 * area = sum (X[n] * Y[n+1] - X[n+1] * Y[n])}.
617 * If the area is negative the way is ordered in a clockwise direction.
618 *
619 * See http://paulbourke.net/geometry/polyarea/
620 *
621 * @param w the way to be checked.
622 * @return true if and only if way is oriented clockwise.
623 * @throws IllegalArgumentException if way is not closed (see {@link Way#isClosed}).
624 */
625 public static boolean isClockwise(Way w) {
626 if (!w.isClosed()) {
627 throw new IllegalArgumentException("Way must be closed to check orientation.");
628 }
629
630 double area2 = 0.;
631 int nodesCount = w.getNodesCount();
632
633 for (int node = 1; node <= /*sic! consider last-first as well*/ nodesCount; node++) {
634 LatLon coorPrev = w.getNode(node - 1).getCoor();
635 LatLon coorCurr = w.getNode(node % nodesCount).getCoor();
636 area2 += coorPrev.lon() * coorCurr.lat();
637 area2 -= coorCurr.lon() * coorPrev.lat();
638 }
639 return area2 < 0;
640 }
641
642 /**
643 * Returns angle of a segment defined with 2 point coordinates.
644 *
645 * @param p1
646 * @param p2
647 * @return Angle in radians (-pi, pi]
648 */
649 public static double getSegmentAngle(EastNorth p1, EastNorth p2) {
650
651 CheckParameterUtil.ensureValidCoordinates(p1, "p1");
652 CheckParameterUtil.ensureValidCoordinates(p2, "p2");
653
654 return Math.atan2(p2.north() - p1.north(), p2.east() - p1.east());
655 }
656
657 /**
658 * Returns angle of a corner defined with 3 point coordinates.
659 *
660 * @param p1
661 * @param p2 Common endpoint
662 * @param p3
663 * @return Angle in radians (-pi, pi]
664 */
665 public static double getCornerAngle(EastNorth p1, EastNorth p2, EastNorth p3) {
666
667 CheckParameterUtil.ensureValidCoordinates(p1, "p1");
668 CheckParameterUtil.ensureValidCoordinates(p2, "p2");
669 CheckParameterUtil.ensureValidCoordinates(p3, "p3");
670
671 Double result = getSegmentAngle(p2, p1) - getSegmentAngle(p2, p3);
672 if (result <= -Math.PI) {
673 result += 2 * Math.PI;
674 }
675
676 if (result > Math.PI) {
677 result -= 2 * Math.PI;
678 }
679
680 return result;
681 }
682
683 /**
684 * Compute the centroid/barycenter of nodes
685 * @param nodes Nodes for which the centroid is wanted
686 * @return the centroid of nodes
687 */
688 public static EastNorth getCentroid(List<Node> nodes) {
689
690 BigDecimal area = BigDecimal.ZERO;
691 BigDecimal north = BigDecimal.ZERO;
692 BigDecimal east = BigDecimal.ZERO;
693
694 // See http://en.wikipedia.org/w/index.php?title=Centroid&oldid=294224857#Centroid_of_polygon for the equation used here
695 for (int i = 0; i < nodes.size(); i++) {
696 EastNorth n0 = nodes.get(i).getEastNorth();
697 EastNorth n1 = nodes.get((i+1) % nodes.size()).getEastNorth();
698
699 if (n0.isValid() && n1.isValid()) {
700 BigDecimal x0 = new BigDecimal(n0.east());
701 BigDecimal y0 = new BigDecimal(n0.north());
702 BigDecimal x1 = new BigDecimal(n1.east());
703 BigDecimal y1 = new BigDecimal(n1.north());
704
705 BigDecimal k = x0.multiply(y1, MathContext.DECIMAL128).subtract(y0.multiply(x1, MathContext.DECIMAL128));
706
707 area = area.add(k, MathContext.DECIMAL128);
708 east = east.add(k.multiply(x0.add(x1, MathContext.DECIMAL128), MathContext.DECIMAL128));
709 north = north.add(k.multiply(y0.add(y1, MathContext.DECIMAL128), MathContext.DECIMAL128));
710 }
711 }
712
713 BigDecimal d = new BigDecimal(3, MathContext.DECIMAL128); // 1/2 * 6 = 3
714 area = area.multiply(d, MathContext.DECIMAL128);
715 if (area.compareTo(BigDecimal.ZERO) != 0) {
716 north = north.divide(area, MathContext.DECIMAL128);
717 east = east.divide(area, MathContext.DECIMAL128);
718 }
719
720 return new EastNorth(east.doubleValue(), north.doubleValue());
721 }
722
723 /**
724 * Returns the coordinate of intersection of segment sp1-sp2 and an altitude
725 * to it starting at point ap. If the line defined with sp1-sp2 intersects
726 * its altitude out of sp1-sp2, null is returned.
727 *
728 * @param sp1
729 * @param sp2
730 * @param ap
731 * @return Intersection coordinate or null
732 */
733 public static EastNorth getSegmentAltituteIntersection(EastNorth sp1, EastNorth sp2, EastNorth ap) {
734
735 CheckParameterUtil.ensureValidCoordinates(sp1, "sp1");
736 CheckParameterUtil.ensureValidCoordinates(sp2, "sp2");
737 CheckParameterUtil.ensureValidCoordinates(ap, "ap");
738
739 Double segmentLenght = sp1.distance(sp2);
740 Double altitudeAngle = getSegmentAngle(sp1, sp2) + Math.PI / 2;
741
742 // Taking a random point on the altitude line (angle is known).
743 EastNorth ap2 = new EastNorth(ap.east() + 1000
744 * Math.cos(altitudeAngle), ap.north() + 1000
745 * Math.sin(altitudeAngle));
746
747 // Finding the intersection of two lines
748 EastNorth resultCandidate = Geometry.getLineLineIntersection(sp1, sp2,
749 ap, ap2);
750
751 // Filtering result
752 if (resultCandidate != null
753 && resultCandidate.distance(sp1) * .999 < segmentLenght
754 && resultCandidate.distance(sp2) * .999 < segmentLenght) {
755 return resultCandidate;
756 } else {
757 return null;
758 }
759 }
760
761 public static class MultiPolygonMembers {
762 public final Set<Way> outers = new HashSet<Way>();
763 public final Set<Way> inners = new HashSet<Way>();
764
765 public MultiPolygonMembers(Relation multiPolygon) {
766 for (RelationMember m : multiPolygon.getMembers()) {
767 if (m.getType().equals(OsmPrimitiveType.WAY)) {
768 if (m.getRole().equals("outer")) {
769 outers.add(m.getWay());
770 } else if (m.getRole().equals("inner")) {
771 inners.add(m.getWay());
772 }
773 }
774 }
775 }
776 }
777
778 /**
779 * Tests if the {@code node} is inside the multipolygon {@code multiPolygon}. The nullable argument
780 * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match.
781 */
782 public static boolean isNodeInsideMultiPolygon(Node node, Relation multiPolygon, Predicate<Way> isOuterWayAMatch) {
783 return isPolygonInsideMultiPolygon(Collections.singletonList(node), multiPolygon, isOuterWayAMatch);
784 }
785
786 /**
787 * Tests if the polygon formed by {@code nodes} is inside the multipolygon {@code multiPolygon}. The nullable argument
788 * {@code isOuterWayAMatch} allows to decide if the immediate {@code outer} way of the multipolygon is a match.
789 * <p>
790 * If {@code nodes} contains exactly one element, then it is checked whether that one node is inside the multipolygon.
791 */
792 public static boolean isPolygonInsideMultiPolygon(List<Node> nodes, Relation multiPolygon, Predicate<Way> isOuterWayAMatch) {
793 // Extract outer/inner members from multipolygon
794 MultiPolygonMembers mpm = new MultiPolygonMembers(multiPolygon);
795 // Test if object is inside an outer member
796 for (Way out : mpm.outers) {
797 if (nodes.size() == 1
798 ? nodeInsidePolygon(nodes.get(0), out.getNodes())
799 : EnumSet.of(PolygonIntersection.FIRST_INSIDE_SECOND, PolygonIntersection.CROSSING).contains(polygonIntersection(nodes, out.getNodes()))) {
800 boolean insideInner = false;
801 // If inside an outer, check it is not inside an inner
802 for (Way in : mpm.inners) {
803 if (polygonIntersection(in.getNodes(), out.getNodes()) == PolygonIntersection.FIRST_INSIDE_SECOND
804 && (nodes.size() == 1
805 ? nodeInsidePolygon(nodes.get(0), in.getNodes())
806 : polygonIntersection(nodes, in.getNodes()) == PolygonIntersection.FIRST_INSIDE_SECOND)) {
807 insideInner = true;
808 break;
809 }
810 }
811 // Inside outer but not inside inner -> the polygon appears to be inside a the multipolygon
812 if (!insideInner) {
813 // Final check using predicate
814 if (isOuterWayAMatch == null || isOuterWayAMatch.evaluate(out)) {
815 return true;
816 }
817 }
818 }
819 }
820 return false;
821 }
822}
Note: See TracBrowser for help on using the repository browser.