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

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

see #15182 - deprecate Main.getLayerManager(). Replacement: gui.MainApplication.getLayerManager()

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