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

Last change on this file since 12411 was 12382, checked in by michael2402, 7 years ago

More documentation for the tools package

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