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

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

use INode interface in Geometry class

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